Properties in Java
Properties in Java is a subclass of Hashtable.It stores String values against String keys.The contents of a Properties object can be directly saved to a file and a properties file can be directly loaded to a properties object.Since Properties is a subclass of Hashtable, the methods put() and putAll() is applicable to Properties too. These methods allow the insertion of non-String keys as well as values.So the use of put() and putAll() is highly discouraged.
The program shown below reads a properties file and displays the key value pairs.The appending few more keys.The existing myfile.properties file is in C:/tmp folder.
#States in India & Capitals Goa = Panaji Kerala = Trivandrum TN = Chennai #comment
Now see the code shown below.
import java.io.*; import java.util.Enumeration; import java.util.Properties; public class PropRead { Properties properties = null; File file = null; public PropRead() { file = new File("C:/tmp/myfile.properties"); } public void readProperties() { System.out.println("Contents of properties"); properties = new Properties(); try { properties.load(new FileInputStream(file)); Enumeration enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement().toString(); System.out.println("Key : " + key + " ; Value : " + properties.get(key)); } System.out.println("Reading is over"); } catch (IOException e) { e.printStackTrace(); } } public void appendProperties() { properties.setProperty("Karnataka", "Bangalore"); properties.setProperty("Bihar", "Patna"); try { FileOutputStream outputStream = new FileOutputStream(file); properties.store(outputStream, null); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } System.out.println("Added new properties"); } public static void main(String[] args) { PropRead propRead = new PropRead(); propRead.readProperties(); propRead.appendProperties(); propRead.readProperties(); } }
Output
Contents of properties
Key : TN ; Value : Chennai
Key : Goa ; Value : Panaji
Key : Kerala ; Value : Trivandrum
Reading is over
Added new properties
Contents of properties
Key : Karnataka ; Value : Bangalore
Key : TN ; Value : Chennai
Key : Goa ; Value : Panaji
Key : Bihar ; Value : Patna
Key : Kerala ; Value : Trivandrum
Reading is over