How do I load properties from XML file?
Category: java.io, viewed: 2039 time(s).
Reading XML properties can be easily done using the Properties.loadFromXML() method. Just like reading the properties from a file that contains a key=value pairs, the XML file will also contains a key and value wrapped in the following XML format.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Application Configuration</comment> <entry key="data.folder">D:\App\Data</entry> <entry key="jdbc.url">jdbc:mysql://localhost/mydb</entry> </properties>
package org.kodejava.example.io; import java.io.FileInputStream; import java.util.Properties; public class LoadXmlProperties { public static void main(String[] args) { LoadXmlProperties lxp = new LoadXmlProperties(); try { Properties properties = lxp.readProperties(); /* * Display all properties information */ properties.list(System.out); /* * Read the value of data.folder and jdbc.url configuration */ String dataFolder = properties.getProperty("data.folder"); System.out.println("dataFolder = " + dataFolder); String jdbcUrl = properties.getProperty("jdbc.url"); System.out.println("jdbcUrl = " + jdbcUrl); } catch (Exception e) { e.printStackTrace(); } } public Properties readProperties() throws Exception { Properties properties = new Properties(); FileInputStream fis = new FileInputStream("configuration.xml"); properties.loadFromXML(fis); return properties; } } |
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I store properties as XML file?
- How do I convert InputStream to String?
- How do I convert string into InputStream?
- How do I get an exception stack trace message?
- How do I use Console class to read user input?
- How do I store objects in file?
- How do I use DataInputStream and DataOutputStream?
- How do I use RandomAccessFile class?
- How do I create a directories recursively?
- How can I get current working directory?