Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Reading a properties file so that keys can be retrieved in order

3,872 views
Skip to first unread message

laredo...@gmail.com

unread,
May 12, 2011, 3:53:59 PM5/12/11
to
Hi,

I'm using Java 1.6. Let's say I have a properties file ...

a=1
b=2
c=3
...

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")?

Thanks, - Dave

Lew

unread,
May 12, 2011, 4:14:52 PM5/12/11
to

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


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.

--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

Lew

unread,
May 12, 2011, 9:13:16 PM5/12/11
to
laredo...@zipmail.com wrote:
>> I'm using Java 1.6. Let's say I have a properties file ...
>>
>> a=1
>> b=2
>> c=3
>> ...
>>
>> How can i [sic] 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")?

<sscce source="com/lewscanon/eegee/Properteer.java">
/* Properteer.java
* $Id$
*/
package com.lewscanon.eegee;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;

/**
* Properteer.
*/
public class Properteer
{
private static final String PROPFILE = "properteer.properties";

/**
* main.
* @param args String [] command arguments.
*/
public static void main( String [] args )
{
Reader propReader = new InputStreamReader(
Properteer.class.getResourceAsStream( PROPFILE ));

assert propReader != null;

Properties props = new Properties();
try
{
props.load( propReader );
}
catch ( IOException exc )
{
final String msg = "Unable to load properties: "
+ exc.getLocalizedMessage();
System.err.println( msg );
IllegalStateException rethrow = new IllegalStateException( msg,
exc );
throw rethrow;
}
finally
{
close( propReader );
}

System.out.println( "size "+ props.size() +": " );
System.out.println( "------" );
System.out.println( "native order" );
for ( Map.Entry <?, ?> entry : props.entrySet() )
{
System.out.println( entry.getValue().toString() );
}
System.out.println( "------" );

System.out.println( "forced order" );


for ( Orderer ord : Orderer.values() )
{

System.out.println( props.get( ord.toString() ));
}
System.out.println( "------" );
System.out.println();

}

static void close( Closeable closeable )
{
assert closeable != null; // package-private - cannot accept null
try
{
closeable.close();
}
catch ( IOException exc )
{
final String msg = "Unable: "+ exc.getLocalizedMessage();
System.err.println( msg );
}
}

enum Orderer
{
FOO("foo"), BAR("bar"), BAZ("baz"), QUX("qux"), ;

private final String handle;

Orderer( String han )
{
this.handle = han;
}

@Override
public final String toString()
{
return this.handle;
}

/**
* fromString - convert from {@code String} to {@code Orderer}.
* Tries custom strings first, then defaults to {@code valueOf()}.
* @param han String to convert.
* @return Orderer matching the input, or {@code null} if no match.
*/
public static Orderer fromString( String han )
{
if ( han == null )
{
return null;
}
for ( Orderer inst : values() )
{
if ( han.equals( inst.toString() ) )
{
return inst;
}
}
return valueOf( han );
}
}

}
</sscce>

properteer.properties (in same subdirectory as Properteer.class):
----------------------
foo = The Fonz
bar = Richie Cunningham
baz = Joanie Cunningham
qux = Chachie
----------------------

output:
----------------------
size 4:
------
native order
Chachie
Richie Cunningham
Joanie Cunningham
The Fonz
------
forced order
The Fonz
Richie Cunningham
Joanie Cunningham
Chachie
------
----------------------

etienne...@gradleware.com

unread,
Dec 12, 2014, 11:41:14 AM12/12/14
to
See https://github.com/etiennestuder/java-ordered-properties for a complete implementation that allows to read/write properties files in a well-defined order.

OrderedProperties properties = new OrderedProperties();
properties.load(new FileInputStream(new File("~/some.properties")));

The OrderedProperties class will solve your requirement.

Kind regards, Etienne

Arne Vajhøj

unread,
Dec 12, 2014, 7:02:19 PM12/12/14
to
On 12/12/2014 11:40 AM, etienne...@gradleware.com wrote:
> On Thursday, May 12, 2011 9:53:59 PM UTC+2, laredo...@zipmail.com wrote:
>> I'm using Java 1.6. Let's say I have a properties file ...
>>
>> a=1
>> b=2
>> c=3
>> ...
>>
>> 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")?
>
> See https://github.com/etiennestuder/java-ordered-properties for a complete implementation that allows to read/write properties files in a well-defined order.
>
> OrderedProperties properties = new OrderedProperties();
> properties.load(new FileInputStream(new File("~/some.properties")));
>
> The OrderedProperties class will solve your requirement.

The question is 3.5 years old.

Arne


Robert Klemme

unread,
Dec 16, 2014, 7:14:24 AM12/16/14
to
On 13.12.2014 01:02, Arne Vajhøj wrote:
> On 12/12/2014 11:40 AM, etienne...@gradleware.com wrote:

>> OrderedProperties properties = new OrderedProperties();
>> properties.load(new FileInputStream(new File("~/some.properties")));

The input stream is not properly closed as far as I can see.

>> The OrderedProperties class will solve your requirement.
>
> The question is 3.5 years old.

Maybe it took him so long...

I am more concerned with the usefulness of this approach. Properties
are simply unordered and I think no special semantic should be applied
to that order. This is fragile. If order is needed it is much better
to choose property names accordingly and this is also what most people
seem to do.

foo.bar.name.2=World
foo.bar.name.1=Hello
foo.bar.name.3=!

If it gets fancier than that then maybe properties are not the proper tool.

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

0 new messages