How to write java.util.Properties to XML with sorted keys?

Question :

How to write java.util.Properties to XML with sorted keys?,

Answer :

I’d like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order?

String propFile = "/path/to/file";  Properties props = new Properties();  /*set some properties here*/  try {      FileOutputStream xmlStream = new FileOutputStream(propFile);      /*this comes out unsorted*/      props.storeToXML(xmlStream,"");  } catch (IOException e) {      e.printStackTrace();  }  

,

Here’s a quick and dirty way to do it:

String propFile = "/path/to/file";  Properties props = new Properties();    /* Set some properties here */    Properties tmp = new Properties() {    @Override    public Set keySet() {      return Collections.unmodifiableSet(new TreeSet(super.keySet()));    }  };    tmp.putAll(props);    try {      FileOutputStream xmlStream = new FileOutputStream(propFile);      /* This comes out SORTED! */      tmp.storeToXML(xmlStream,"");  } catch (IOException e) {      e.printStackTrace();  }  

Here are the caveats:

  • The tmp Properties (an anonymous
    subclass) doesn’t fulfill the
    contract of Properties.

For example, if you got its keySet and tried to remove an element from it, an exception would be raised. So, don’t allow instances of this subclass to escape! In the snippet above, you are never passing it to another object or returning it to a caller who has a legitimate expectation that it fulfills the contract of Properties, so it is safe.

  • The implementation of
    Properties.storeToXML could change,
    causing it to ignore the keySet
    method.

For example, a future release, or OpenJDK, could use the keys() method of Hashtable instead of keySet. This is one of the reasons why classes should always document their “self-use” (Effective Java Item 15). However, in this case, the worst that would happen is that your output would revert to unsorted.

  • Remember that the Properties storage
    methods ignore any “default”
    entries.

That’s the answer How to write java.util.Properties to XML with sorted keys?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  Import Namespace System.Query