Java Properties files are amazing resources to add information in Java. Generally these files are used to store static information in key and value pair. Things that you do not want to hard code in your Java code goes into properties files.
Although there are multiple ways of loading properties file, I will be focusing on loading the resource bundle files from class path resources. There are advantages of adding properties files in the classpath:
The properties files became a part of the deployable code (e.g. JAR file) making it easy to manage.
Properties files can be loaded independent of the path of source code.
Let us see the simple way of Loading a property file in Java code. There are two ways of loading properties files in Java.
1. Using ClassLoader.getResourceAsStream()
2. Using Class.getResourceAsStream()
In our example we will use both methods to load a properties file.
Following is the content of sample properties file. The properties file will be in package net.viralpatel.resources.
To load properties file using Classloader, use following code:
The Class.getResourceAsStream(name) returns an Inputstream for a resource with a given name or null if no resource with the given name is found. The name of a resource is a ‘/’-seperated path name that identifies the resource. If the name with a leading “/” indicates the absolute name of the resource is the portion of the name following the ‘/’.
In Class.getResourceAsStream(name), the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object’s class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).
So in our example to load config.properties we will have a method loadProps1().
The ClassLoader.getResourceAsStream(name) returns an Inputstream for reading the specified resource or null if the resource could not be found. The name of a resource is a ‘/’-seperated path name that identifies the resource. The name no leading ‘/’ (all namea are absolute).
So in our example to load config.properties we will have a method loadProps2().