How to use Java property files?
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()
.
You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
Iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
If you put the properties file in the same package as class Foo, you can easily load it with
new Properties().load(Foo.class.getResourceAsStream("file.properties"))
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.