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!
All we have to do is maintain a separate ordered list of the keys, and provide a new "keys()" method.
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.
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.
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();) {
}
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