Searching...
Saturday, 18 January 2014

How to convert Properties files to xml in java?

19:43

The Java.util.Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. In this class storeToXML method helps to convert a stream to file. Here is one simple example to load a test properties file and converting in to xml file.

Input Property file (test.properties)

name=pretech
location=bangalore

Example

package com.pretech;
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 JavaPropertiesToXML {
	public static void main(String[] args) {
		File file = null;
		try {
			System.out.println("Started conversion");
			file = new File("test.properties");
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			Properties pr = new Properties();
			pr.load(br);
			OutputStream os = new FileOutputStream("test.xml");
			pr.storeToXML(os, "Property details", "UTF-8");
			br.close();
			fis.close();
			os.close();
			System.out.println("Completed conversion");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Output (test.xml)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>Property details</comment>
	<entry key="location">bangalore</entry>
	<entry key="name">pretech</entry>
</properties>

0 comments: