Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How maintain the order of keys in Java properties file?

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?

like image 241
user3496599 Avatar asked Aug 06 '14 12:08

user3496599


2 Answers

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

like image 56
emesx Avatar answered Oct 14 '22 05:10

emesx


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();
    }
}
like image 27
Opal Avatar answered Oct 14 '22 05:10

Opal