package au.com.d2klry.properties;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class ReadPropertiesFile {
public static void main(String[] args) {
//First section is creating the properties file
String fileName = "C:\\temp\\java\\properties.txt";
String newFileName = "C:\\temp\\java\\newPropertiesFile.txt";
try {
File propertiesFile = new File(fileName);
if(!propertiesFile.exists()){
propertiesFile.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(propertiesFile));
writer.write("database_name=DB_TEST");
writer.newLine();
writer.write("database_host=localhost");
writer.newLine();
writer.write("database_port=50000");
writer.newLine();
writer.write("#database_username=scott");//Add a comment to properties file
writer.newLine();
writer.write("#database_password=tiger");
writer.flush();
writer.close();
//End of creating properties file
//Second part is reading the properties from the file, printing the properties to the console
//and writing properties to the new file
Properties properties = new Properties();
properties.load(new FileInputStream(fileName));
System.out.println("database_name -- > " + properties.getProperty("database_name"));
System.out.println("database_host -- > " + properties.getProperty("database_host"));
System.out.println("database_port -- > " + properties.getProperty("database_port"));
//Property value will be null as it is not defined in the original properties file
System.out.println("database_username -- > " + properties.getProperty("database_username"));
properties.store(new FileOutputStream(newFileName), "File created by d2klry");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Monday, October 31, 2011
Read and Write the properties file.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment