Store a Properties object as a String…
Ever needed to convert a java.util.Properties object directly to an xml string? It’s actually pretty easy and here’s how you do it:
import java.io.ByteArrayOutputStream; import java.util.Properties; public class PropertiesToXMLString { public static void main(String[] argv) { Properties properties = new Properties(); properties.put("firstName", "John"); properties.put("lastName", "Hancock"); properties.put("address", "3241 NoLane Drive"); properties.put("city", "Anytown"); properties.put("county", "Bounty"); properties.put("state", "Alaska"); properties.put("country", "USA"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { properties.storeToXML(byteArrayOutputStream, "Properties to XML string..."); String xmlString = byteArrayOutputStream.toString(); System.out.println(xmlString); } catch(Exception e) { e.printStackTrace(); } } }
Load a Properties object from a String
In addition to storing a properties object to a String, it is just as easy to load a properties object from a string:
import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.InvalidPropertiesFormatException; import java.util.Properties; public class PropertiesFromXMLString { public static void main(String[] argv) { String xmlInputString = ""; xmlInputString += ""http://java.sun.com/dtd/properties.dtd\">"; xmlInputString += ""; xmlInputString += " "; Properties properties = new Properties(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlInputString.getBytes()); try { properties.loadFromXML(byteArrayInputStream); String helloValue = (String)properties.get("hello"); System.out.println("Hello value: "+helloValue); } catch(Exception e) { e.printStackTrace(); } } }XML string to properties... "; xmlInputString += "world "; xmlInputString += "