Sunday, May 31, 2009

How to read Properties file in Java using ResourceBundle and Properties class

There are many ways to read properties file in java. Here explained two way, using

1. ResourceBundle
2. Properties Class
3. How to write properties file is also mentioned in ReadPropFile.java

How to use this tutorial
1. Create one directory src and put both below files (MyProp.properties and ReadPropFile.java)

2. MyProp.properties
name = Binod Kumar Suman
roll = 110
city = Bangalore

3. ReadPropFile.java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;


public class ReadPropFile {

public static void main(String[] args) {
// readpropFile();
otherway();
}

public static void readpropFile(){
ResourceBundle bundle = ResourceBundle.getBundle("MyProp");
String studentName = bundle.getString("name");
String roll = bundle.getString("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

// Fetch all the Properties.

Enumeration keys = bundle.getKeys();
while(keys.hasMoreElements()){
System.out.println(keys.nextElement());
}

}

public static void otherway(){
try{
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("src/MyProp.properties"));
String studentName = propertiesFile.getProperty("name");
String roll = propertiesFile.getProperty("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

//Fetch all the Properties.

String key;
Enumeration e = propertiesFile.propertyNames();
while (e.hasMoreElements()) {
key = (String)e.nextElement();
System.out.println(key+" "+propertiesFile.getProperty(key));
}

// Write to properties file
propertiesFile.setProperty("Compnay","Satyam");
propertiesFile.store(new FileOutputStream("src/MyProp.properties"),null);


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

6 comments:

  1. Could you please send the URL to download this source code? Thanks,

    ReplyDelete
  2. Hi, Thanks, Thanks o lot for putting code snipet, it helps me lot to solve my current problem.

    Did u work for Satyam? I am a X-Satyamaites.

    Regards,
    Prodip Saha
    prodipaims@rediffmail.com
    +880 1824604014

    ReplyDelete
  3. Hi Prodip, Yes I am Satyamites. How was your experiance with Satyam?

    With Regards,

    Binod Suman
    http://binodsuman.blogspot.com

    ReplyDelete
  4. Hi

    how to write 2 or more values into properties file using propertiesFile.setProperty("Compnay","Satyam");
    for example, my property file should look like this

    MyProp.properties
    Company=Satyam
    Company=Wipro
    Company=HP

    ReplyDelete
  5. Hi,
    Thanks,this code help me lot.

    ReplyDelete
  6. Hi,

    Where did you stored your properties file while accessing using Properties class

    ReplyDelete

Please put your feedback or your any question related to this blog. Thanks.