Tuesday, 6 March 2012

java program to convert properties file into xml file

userinfo.properties

username=sachin
password=india@123
age=38

package com.usr.properties;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesToXML {
       public static void main(String[] args) {
              File file=new File("userinfo.properties");
              try{
                     FileInputStream fis=new FileInputStream(file);
                     BufferedReader br=new BufferedReader(new InputStreamReader(fis));
                     Properties pr=new Properties();
                     pr.load(br);
                     OutputStream os=new FileOutputStream("userinfo.xml");
                     pr.storeToXML(os,"User Info", "UTF-8");
                     System.out.println("converted to xml");
                     br.close();
                     fis.close();
                     os.close();
              }
              catch(FileNotFoundException ex){
                     ex.printStackTrace();
              }
              catch (IOException ex) {
                     ex.printStackTrace();
              }

       }
}

OUTPUT
userinfo.xml 
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>User Info</comment>
<entry key="age">38</entry>
<entry key="password">india@123</entry>
<entry key="username">sachin</entry>
</properties>