Example of Properties in Java
June 09, 2013
java.util.Properties stores key value pair. Properties inherit HashTable, so Properties has the methods of HashTable. Properties are persistent storage of key value pair. It means we can export the value through byte stream. Properties can be stored in XML as well. Find the example below.
PropertiesDemo.java
package com.concretepage.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import java.util.Properties; public class PropertiesDemo { public static void main(String[] args) throws IOException { Properties prop = new Properties(); prop.put("A","AAA"); prop.put("B","BBB"); prop.put("C", "CCC"); //iterate Properties for(Map.Entry<Object,Object> mapEntry : prop.entrySet() ){ System.out.println(mapEntry.getKey() +" "+mapEntry.getValue()); } //get value by key System.out.println(prop.get("A")); //export file in XML FileOutputStream fos = new FileOutputStream(new File("C:/propFile.xml")); prop.storeToXML(fos, "Properties exported."); System.out.println("Done"); } }
Output
A AAA C CCC B BBB AAA Done
Output in XML(C:/propFile.xml)
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Properties exported.</comment> <entry key="A">AAA</entry> <entry key="C">CCC</entry> <entry key="B">BBB</entry> </properties>