I have a properties file where the order of the values is important. I want to be able to iterate through the properties file and output the values based on the order of the original file.
However, since the Properties file is backed by, correct me if I'm wrong, a Map that does not maintain insertion order, the iterator returns the values in the wrong order.
Here is the code I'm using
Enumeration names = propfile.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
//do stuff
}
Is there anyway to get the Properties back in order short of writting my own custom file parser?
In some answers it is assumed that properties read from file are put to instance of
Properties
(by calls toput
) in order they appear they in file. While this is in general how it behaves I don't see any guarantee for such order.IMHO: it is better to read the file line by line (so that the order is guaranteed), than use the Properties class just as a parser of single property line and finally store it in some ordered Collection like
LinkedHashMap
.This can be achieved like this:
Just note that the method posted above takes an
InputStream
which should be closed afterwards (of course there is no problem to rewrite it to take just a file as an argument).Nope - maps are inherently "unordered".
You could possibly create your own subclass of
Properties
which overrodesetProperty
and possiblyput
, but it would probably get very implementation-specific...Properties
is a prime example of bad encapsulation. When I last wrote an extended version (about 10 years ago!) it ended up being hideous and definitely sensitive to the implementation details ofProperties
.Extend
java.util.Properties
, override bothput()
andkeys()
:Dominique Laurent's solution above works great for me. I also added the following method override:
Probably not the most efficient, but it's only executed once in my servlet lifecycle.
Thanks Dominique!
In the interest of completeness ...
I dont think the methods returning set should be overridden as a set by definition does not maintain insertion order
As I see it,
Properties
is to much bound toHashtable
. I suggest reading it in order to aLinkedHashMap
. For that you'll only need to override a single method,Object put(Object key, Object value)
, disregarding theProperties
as a key/value container:Usage: