Tuesday, August 28, 2012

Java with property file

This is a basic property file sample. You can take the source then
do the necessary changes and apply to your code
PropertyFileSample.java

[sourcecode language="java"]
package mysamples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
*
* @author dinuka
*/
public class PropertyFileSample {

public static void write() {
Properties prop = new Properties();

try {
//set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "root");
prop.setProperty("dbpassword", "123");

//save properties to project root folder
prop.store(new FileOutputStream("config.properties"), null);

} catch (IOException ex) {
ex.printStackTrace();
}
}

public static void read() {

Properties prop = new Properties();
try {
prop.load(new FileInputStream("config.properties"));
String database = prop.getProperty("database");
String user = prop.getProperty("dbuser");
String pw = prop.getProperty("dbpassword");
System.out.println("Database: " + database);
System.out.println("DB User: " + user);
System.out.println("DB User: " + pw);
} catch (Exception e) {
}

}

public static void main(String[] args) {
PropertyFileSample.write();
PropertyFileSample.read();
}
}
[/sourcecode]

Output file
[sourcecode language="java"]
#Tue Aug 28 17:33:26 IST 2012
dbpassword=123
database=localhost
dbuser=root
[/sourcecode]

1 comment: