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

Let's take the first example. Just create a file right in the the src folder of your application. When you compile the application the file will be copied by the compiler in the classes folder of the web app. This is where the '/' is loaded from. In a similar manner we can dedicate a folder inside the src folder to all the properties file(in that case we specify the full path like that: "/config/").

Properties properties = new Properties() ;

Similar example to use in a static context:

Properties properties = new Properties() ;

Now we came to the second example similar to the first one, when we create the properties file in the src folder in the same location(package) where the specific class is created. The compiler will again take the task to copy the properties file in the classes folder of the webapp. As long as we load it from the same folder with the current class we no longer need to specify an location relative to the "root" folder.

Properties properties = new 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\\"));