I have Groovy code to read the property file and change the values and then write it to 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 the properties to file it change the order of the keys. Is there any way to maintain the same order as initial file.
I'm new to groovy please can some one give the suggestion to this?
I checked the Properties
class and it turns out it extends Hashtable
which doesn't make any guarantees as to the ordering of its elements. So that's why the output file has the keys mixed up.
In my opinion you'd have to override at least two methods: put
, which is called for every property (in order they occur), and keys
which is called during saving. You'd simply use this class instead of Properties
then.
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 works fine, but I surely didn't think of all possible cases. We are extending Hashtable
here (beware!), not an usual decision I'd say...
Maybe use decorated properties:
class SortedProperties extends Properties {
@Override
public synchronized Enumeration keys() {
Enumeration keysEnum = super.keys();
Vector keyList = new Vector();
while (keysEnum.hasMoreElements()) {
keyList.add(keysEnum.nextElement());
}
keyList.sort()
return keyList.elements();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With