Grails – how do I maintain the order of keys in a Java properties file?
I have groovy code to read the properties file, change the value, and then write it to the same file
def props = new Properties() File propsFile = new File('C:/Groovy/config.properties') props.load(propsFile.newDataInputStream()) props.each { key,value -> if("${key}" == "ABC"){ props.setProperty("${key}","XYZ") } } props.store(propsFile.newWriter(),null)
When I write properties to a file, it changes the order of keys Is there any way to maintain the same order as the original documents
I'm new to groovy. Would anyone please give me this suggestion?
Solution
I checked the attribute class and proved that it extends hashtable, which makes no guarantee for the ordering of its elements So that's why the output file confuses keys
In my opinion, you must override at least two methods: put, called for each property (in order), and the key called during save You only need to use this class instead of properties
import java.util.*; public class OrderedProperties extends Properties { private final LinkedHashSet<Object> keyOrder = new LinkedHashSet<>(); @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(keyOrder); } @Override public synchronized Object put(Object key,Object value) { keyOrder.add(key); return super.put(key,value); } }
I just tested it in your scenario and it worked well, but I certainly didn't think of all the possible situations We extend hashtable here (be careful!), This is not the usual decision I'm talking about