How to Convert Property File to XML in Java

Convert Property File to XML in Java

This example program about, How to convert property file to xml in java. The example were tested and output shared in the same post.

1) Converting Property File to XML

public static void convertToXML(final String filePath) {

	// creating the properties object
	Properties properties = new Properties();
	
	// creating file object
	File propertiesFile = new File(filePath);

	FileReader fr = null;
	
	try {
		
		fr = new FileReader(propertiesFile);

		properties.load(fr);
		
		File xmlFile = new File("employee.xml");
		
		FileOutputStream fos = new FileOutputStream(xmlFile);
		
		properties.storeToXML(fos, "This XML File Contain Employee Information");

	} catch (FileNotFoundException e) {
		
		System.out.println(e.getMessage());
		e.printStackTrace();
		
	} catch (IOException e) {

		System.out.println(e.getMessage());
		e.printStackTrace();
	}

}

2) Complete Example

package com.dineshkrish.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class PropertiesToXML {
	
	public static void convertToXML(final String filePath) {
	
		// creating the properties object
		Properties properties = new Properties();
		
		// creating file object
		File propertiesFile = new File(filePath);

		FileReader fr = null;
		
		try {
			
			fr = new FileReader(propertiesFile);

			properties.load(fr);
			
			File xmlFile = new File("employee.xml");
			
			FileOutputStream fos = new FileOutputStream(xmlFile);
			
			properties.storeToXML(fos, "This XML File Contain Employee Information");

		} catch (FileNotFoundException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
			
		} catch (IOException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	
	}

	public static void main(String[] args) {

		String filePath = "employee.properties";
		
		PropertiesToXML.convertToXML(filePath);
		
		System.out.println("Properties File Convert to XML File Successfully...");
	}
}

3) Sample Property File

How to Convert Property File to XML in Java

Output

Properties File Convert to XML File Successfully…

Convert Property File to XML in Java

References

1. Java Properties Class
2. Java File Class
3. Java FileReader Class
4. Java FileOutputStream Class

Hello everyone, I am a Founder of dineshkrish.com.