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:
Here are the caveats:
For example, if you got its
keySetand 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.For example, a future release, or OpenJDK, could use the
keys()method ofHashtableinstead ofkeySet. 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.