RSS

Java with property file

28 Aug

This is a basic property file sample. You can take the source then
do the necessary changes and apply to your code
PropertyFileSample.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();
}
}

Output file

#Tue Aug 28 17:33:26 IST 2012
dbpassword=123
database=localhost
dbuser=root
Advertisements
 
1 Comment

Posted by on August 28, 2012 in java

 

Tags:

One response to “Java with property file

  1. malalanayake

    August 28, 2012 at 11:56 am

    if you have any java problems please leave a comment

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: