How can I write Java properties in a defined order?

Steve McLeod picture Steve McLeod · Jun 9, 2013 · Viewed 28.2k times · Source

I'm using java.util.Properties's store(Writer, String) method to store the properties. In the resulting text file, the properties are stored in a haphazard order.

This is what I'm doing:

Properties properties = createProperties();
properties.store(new FileWriter(file), null);

How can I ensure the properties are written out in alphabetical order, or in the order the properties were added?

I'm hoping for a solution simpler than "manually create the properties file".

Answer

Steve McLeod picture Steve McLeod · Jun 9, 2013

As per "The New Idiot's" suggestion, this stores in alphabetical key order.

Properties tmp = new Properties() {
    @Override
    public synchronized Enumeration<Object> keys() {
        return Collections.enumeration(new TreeSet<Object>(super.keySet()));
    }
};
tmp.putAll(properties);
tmp.store(new FileWriter(file), null);