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<Object> keySet()
{
return Collections.unmodifiableSet(new TreeSet<Object>(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.