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

10 comments:

  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
  2. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
    Java training in Chennai

    Java training in Bangalore

    ReplyDelete
  3. Really i appreciate the effort you made to share the knowledge. The topic here i found was really effective...

    Get SAP HANA Admin Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  4. I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.

    oracle training in bangalore

    ReplyDelete
  5. Really good article with good information

    Thank You


    data science course in indore

    ReplyDelete