Java Collection How to - Use XML with Properties








Question

We would like to know how to use XML with Properties.

Answer

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;
/*  w  w w.j a v  a  2 s .  c  o  m*/
public class Main {
  public static void main(String args[]) throws Exception {
    Properties p = new Properties();

    p.put("today", new Date().toString());
    p.put("user", "A");

    FileOutputStream out = new FileOutputStream("user.props");
    p.storeToXML(out, "updated");

    FileInputStream in = new FileInputStream("user.props");

    p.loadFromXML(in);
    p.list(System.out);
  }
}

The XML looks like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd
<properties>
    <comment>your wordings</comment>
    <entry key="userA</entry>
    <entry key="today12/12/2009</entry>
</properties>

The code above generates the following result.