Java example to create .properties
file from a given XML file. This code can be used to read properties key-values from XML file, to be used in the application code.
To convert a properties file to XML file, follow the steps given in the linked tutorial.
1. Convert from Properties to XML Example
To convert XML file into a properties file, the best way is to use java.util.Properties
class.
The process is :
- Load XML file into
java.util.Properties
class object, usingProperties.loadFromXML()
method. - Use
Properties.store()
method to write the content as properties.
String outPropertiesFile = "application.properties";
String inXmlFile = "applicationProperties.xml";
InputStream inStream = new FileInputStream(inXmlFile); //Input XML File
OutputStream outStream = new FileOutputStream(outPropertiesFile); //Output properties File
Properties props = new Properties();
//Load XML file
props.loadFromXML(inStream);
//Store to properties file
props.store(outStream, "Converted from applicationProperties.xml");
//Use properties in code
System.out.println(props.get("input.dir")); //Prints 'c:/temp/input'
2. Demo
The input XML file is as follows that we will convert to the properties file.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>application.properties</comment>
<entry key="input.dir">c:/temp/input</entry>
<entry key="spring.batch.job.enabled">false</entry>
<entry key="spring.main.banner-mode">off</entry>
</properties>
The converted output properties file is as follows:
#Converted from applicationProperties.xml
#Mon Jul 23 18:15:00 IST 2018
spring.batch.job.enabled=false
input.dir=c\:/temp/input
spring.main.banner-mode=off
Drop me your questions in the comment section.
Happy Learning !!