Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write Java properties in a defined order?

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".

like image 673
Steve McLeod Avatar asked Jun 09 '13 15:06

Steve McLeod


People also ask

How do you define a class property in Java?

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.

What is Property List in Java?

Properties is a subclass of Hashtable. It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file. Properties class can specify other properties list as it's the default.


2 Answers

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); 
like image 83
Steve McLeod Avatar answered Oct 08 '22 17:10

Steve McLeod


See https://github.com/etiennestuder/java-ordered-properties for a complete implementation that allows to read/write properties files in a well-defined order.

OrderedProperties properties = new OrderedProperties(); properties.load(new FileInputStream(new File("~/some.properties"))); 
like image 24
Etienne Studer Avatar answered Oct 08 '22 17:10

Etienne Studer