javacodex.com
Java Examples
Java Examples
memu home questions

Reading Properties From a XML File

The 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.

Source: (ReadProperties.java)

import java.io.*;
import java.util.*;
 
public class ReadProperties {
   public static void main(String[] args) {
      try {
         File file = new File("props.xml");
         FileInputStream fis = new FileInputStream(file);
         Properties props = new Properties();
         props.loadFromXML(fis);
         fis.close();
 
         Enumeration eKeys = props.keys();
         while (eKeys.hasMoreElements()) {
            String key = (String) eKeys.nextElement();
            String value = props.getProperty(key);
            System.out.println(key + ": " + value);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
 

Output:

$ cat props.xml 
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>This is a comment</comment>
    <entry key="propA">A</entry>
    <entry key="propB">B</entry>
    <entry key="propC">C</entry>
    <entry key="propD">D</entry>
    <entry key="propE">E</entry>
    <entry key="propF">F</entry>
</properties>


$ java ReadProperties 
propA: A
propF: F
propE: E
propD: D
propC: C
propB: B

Contact: javacodex@yahoo.com