I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.
Questions:
- Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?
- Does the file need to end in any specific extension or is
.txt
OK? - How can I load the file in the code
- And how can I iterate through the values inside?
If you put the properties file in the same package as class Foo, you can easily load it with
Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.
If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.
I have written on this property framework for the last year. It will provide of multiple ways to load properties, and have them strongly typed as well.
Have a look at http://sourceforge.net/projects/jhpropertiestyp/
JHPropertiesTyped will give the developer strongly typed properties. Easy to integrate in existing projects. Handled by a large series for property types. Gives the ability to one-line initialize properties via property IO implementations. Gives the developer the ability to create own property types and property io's. Web demo is also available, screenshots shown above. Also have a standard implementation for a web front end to manage properties, if you choose to use it.
Complete documentation, tutorial, javadoc, faq etc is a available on the project webpage.
You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.
Iterate as:
You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use
Class.getResourceAsStream()
orClassLoader.getResourceAsStream()
to access it. If it's on the file system it's slightly easier.Any extension is fine, although .properties is more common in my experience
Load the file using
Properties.load
, passing in anInputStream
or aStreamReader
if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and aReader
instead of the default ISO-8859-1 encoding for a stream.)Iterate through it as you'd iterate through a normal
Hashtable
(whichProperties
derives from), e.g. usingkeySet()
. Alternatively, you can use the enumeration returned bypropertyNames()
.1) It is good to have your property file in classpath but you can place it anywhere in project.
Below is how you load property file from classpath and read all properties.
2) Property files have the extension as .properties
In order: