In my previous tutorials I have explained about how to use DOM Parser and SAX Parser. This tutorial explain with very simple utility method available in the Java package used for converting your existing properties file to a XML file. Sometimes this may be the requirement for Java developers, instead of manually converting properties file to XML, you can use this simple utility class to input the properties file and get the result in the XML file. This utility available in the java.util.Properties and the method name is storeToXML(). Look at the below example.
1. Create A Simple Properties File
key1=Message1 key2=Message2 key3=Message3
2. Write Utility For Conversion
PropToXmlDemo.java
package javabeat.net.xml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class PropToXmlDemo { public static void main(String[] args) throws IOException { Properties props = new Properties(); try{ props.load(PropToXmlDemo.class.getClassLoader().getResourceAsStream("javabeat/net/xml/messages.properties")); }catch (Exception e){ e.printStackTrace(); } //Path for the output file File file = new File("msg.xml"); file.createNewFile(); OutputStream out = new FileOutputStream(file); //Call the utility method to store the properties values to XML file props.storeToXML(out, "Message Properties","UTF-8"); } }
3. Outout XML File
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Message Properties</comment> <entry key="key3">Message3</entry> <entry key="key2">Message2</entry> <entry key="key1">Message1</entry> </properties>
4. Folder Structure
Look at the folder structure for the above example.
If you have any questions, please write it in the comments section.