Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a properties file in java in the original order [duplicate]

I need to read a properties file and generate a Properties class in Java. I do so by using:

Properties props = new Properties();
props.load(new FileInputStream(args[0]));
for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
}

However, the properties returned by props.propertyName is not in the order of the original properties file. I understand that Properties are just old fashioned, non-generified Hashtables. I'm looking for a work around. Any idea? Thank you!

like image 274
wen Avatar asked Sep 01 '10 15:09

wen


People also ask

How do you read a properties file in Java in the original order?

All we have to do is maintain a separate ordered list of the keys, and provide a new "keys()" method.

How do you read the Properties of an object 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.

How do you get all values from properties file in Java?

Get All Key Values from Properties File Get All Key Values from Properties File in java using the Properties class Available in java. util Package. The Properties class extends the Hashtable class. From Hashtable, Properties class inherits the Method KeySet() which Returns a Set view of the keys Contained in this Map.


1 Answers

Example from www.java2s.com should solve your problem.

import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

/**
 * <a href="OrderedProperties.java.html"><b><i>View Source</i></b></a>
 *
 * @author Brian Wing Shun Chan
 *
 */
public class OrderedProperties extends Properties {

    public OrderedProperties() {
        super ();

        _names = new Vector();
    }

    public Enumeration propertyNames() {
        return _names.elements();
    }

    public Object put(Object key, Object value) {
        if (_names.contains(key)) {
            _names.remove(key);
        }

        _names.add(key);

        return super .put(key, value);
    }

    public Object remove(Object key) {
        _names.remove(key);

        return super .remove(key);
    }

    private Vector _names;

}

And your code will change to:

Properties props = new OrderedProperties();
props.load(new FileInputStream(args[0]));
for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
}
like image 149
YoK Avatar answered Oct 22 '22 08:10

YoK