Java properties files are just simple text files that are widely used in Java to store different properties which should not be hard coded in java source files. By convention, properties files should have the .properties extension. They have a simple structure, each line defining a key/value pair. It is also possible to define larger text values on multiple lines. The main benefit of the properties files is the one that they can be easily edited by hand using any text editor.

Java properties files can be stored in

  • in a standard folder, to a known location
  • in classpath (this way it can be packed in a jar file, made is accessible when the application runs)

There are several options to handle the Java properties files:

To read java properties files from the classpath:

The properties files can be stored in the classpath. This way they can be put inside jar files and it’s really useful for web applications when the absolute location of the properties files is not known. When I tested this in an web application it didn’t work:

Properties properties = new Properties() ;
URL url =  ClassLoader.getSystemResource("test.properties");
properties.load(new FileInputStream(new File(url.getFile())));

To read java properties files from the classpath in a web application:

The following example works to load the properties files in a web application. This snippet was tested on Tomcat 5.5. The ‘/’ represents the root of the class path. Otherwise the properties file location is considered relatively to “this” class (or to MyClass for the second example):

Properties properties = new Properties() ;
properties.load(this.getClass().getResourceAsStream("/seoimproved.properties"));

Similar example to use in a static context:

Properties properties = new Properties() ;
properties.load(MyClass.class.getResourceAsStream("/seoimproved.properties"));

To read java properties files from a specific location:

The properties files can be loaded from any location.

Properties properties = new Properties() ;
properties.load(new FileInputStream("C:\\tmp\\test.properties"));

Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on