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();
}
}
}
Sunday, May 31, 2009
Subscribe to:
Post Comments (Atom)
Could you please send the URL to download this source code? Thanks,
ReplyDeleteHi, Thanks, Thanks o lot for putting code snipet, it helps me lot to solve my current problem.
ReplyDeleteDid u work for Satyam? I am a X-Satyamaites.
Regards,
Prodip Saha
prodipaims@rediffmail.com
+880 1824604014
Hi Prodip, Yes I am Satyamites. How was your experiance with Satyam?
ReplyDeleteWith Regards,
Binod Suman
http://binodsuman.blogspot.com
Hi
ReplyDeletehow 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
Hi,
ReplyDeleteThanks,this code help me lot.
Hi,
ReplyDeleteWhere did you stored your properties file while accessing using Properties class