Saturday, April 24, 2010

Using property files in Java web applications

The use of property files avoids hardcoding content in Java classes. One way of using property file is loading it as a normal file with absolute file paths, which is not optimal. The other way, which involves classloaders, we avoid putting environment specific details into our code. This way, we make our code more portable.

Let us create an example property file Resource.properties:

name=John Doe
email=j.doe@company.com
description=John Doe is a \
Java software developer

The property file contains key value pairs separated by '='. When the value is spread among multiple lines we use a backslash to indicate the content continues on the next line. Normally, the property file is put in the CLASS_PATH for the classloader to be found. In Java web applications, the file is stored in WEB-INF/classes. In some cases you want to store the file in the same directory as the class that loads it. In that case, use the relative path (the full package name) to load it. In the example below, the property file is stored in com/package/.

private static final String PROPERTIES_FILE =
"com/package/Resource.properties";

The path to the property file is defined as a static variable in the class that uses it. The class loads the properties in the following way:

Properties properties = new Properties();
properties.load(
this.getClass().getResourceAsStream(PROPERTIES_FILE)
);
String name = props.getProperty("name");
String email = props.getProperty("email");
String description = props.getProperty("description");

1 comment:

  1. Hello! In case you need to make your web app multilingual, I suggest to evaluate a software localization tool like https://poeditor.com/ POEditor to simplify and improve your workflow.

    ReplyDelete