Tuesday, December 06, 2011

Reading and Writing a Properties File

The following code shows how to read and write properties file. With getProperty(key) method we can get the property value by passing property key and like that way with setProperty(key,value) we can set given value to the specified property.

// Read properties file.
  1. Properties properties = new Properties();
  2. try {
  3.     properties.load(new FileInputStream("filename.properties"));
  4.     String s= prproperties.getProperty("Key1");
  5.     System.out.println(s); //Value1
  6. } catch (IOException e) {
  7.     e.printStackTrace();
  8. }
// Write properties file.
  1. try {
  2.     prproperties.setProperty("Key1""ValueXxx");
  3.     properties.store(new FileOutputStream("filename.properties")null);
  4. } catch (IOException e) {
  5.     e.printStackTrace();
  6. }
//filename.properties before write
  1. Key1=Value1
  2. Key2=Value2
  3. Key3=Value3
//filename.properties after write
  1. Key1=ValueXxx
  2. Key2=Value2
  3. Key3=Value3

No comments:

Post a Comment