Re: Reading a properties file so that keys can be retrieved in order
On 05/12/2011 03:53 PM, email@example.com wrote:
I'm using Java 1.6. Let's say I have a properties file ...
How can i read the properties file in Java such that when I retrieve
the key set, the iterator structure would return the keys in the order
they are found in the file (in the above example, "a", "b", "c")?
You'll need custom code. The 'java.util.Properties' type inherits from
'java.util.Hashtable' and there is no guarantee that the table will retain its
order even after you've loaded the properties, let alone the order specified
by the file, depending on its use.
You should explain why the order matters, because the need influences what
sort of data structures and algorithm you'll use.
If the order is determined at compile time, you can use an enum to specify the
property names and retrieve the values by iterating through the enum
'values()' to get the keys, and using those keys to retrieve the properties.
for ( Orderer ord : Orderer.values() )
doSomethingWith( properties.get( ord.toString() ));
If the order is dynamic, you'll have to go through more effort to create a
List <String> orderers = loadOrderers();
for ( String ord : orderers )
doSomethingWith( properties.get( ord ));
Generally with properties or preferences, they should be "load once into a
custom structure", not "load every time you need a property". So load the
properties into an ordered structure at program start or at classload time.
Don't keep the 'Properties' itself around. Then iterate through that custom
structure when you need a property.
Honi soit qui mal y pense.