How to use Java property files? How to use Java property files? java java

How to use Java property files?


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);}


  • 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() or ClassLoader.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 an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)

  • Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().


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.