How to load Properties

To load properties from a file called components.properties in the root of the project, use the following code:

package com.qbytesworld.utils;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.beanutils.PropertyUtils; // NOTE: this is org.appache, not base java
public class Container {
private Map<String, Object> components;
public Container() {
components = new HashMap<String, Object>();
try {
Properties properties = new Properties();
properties.load(new FileInputStream("components.properties"));
for (Map.Entry entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
processEntry(key, value);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void processEntry(String key, String value) throws Exception {
String[] parts = key.split("\\.");
if (parts.length == 1) {
// New component definition
Object component = Class.forName(value).newInstance();
components.put(parts[0], component);
} else {
// Dependency injection
Object component = components.get(parts[0]);
Object reference = components.get(value);
PropertyUtils.setProperty(component, parts[1], reference);
}
}
public Object getComponent(String id) {
return components.get(id);
}
}
Assume our components.properties file looks like:
# Define a new component "reportGenerator"
#reportGenerator=com.report.PdfReportGenerator
reportGenerator=com.report.HtmlReportGenerator
# Define a new component "reportService"
reportService=com.report.ReportService
# Inject the component "reportGenerator" into property "reportGenerator"
reportService.reportGenerator=reportGenerator
Our Map would look like:
Key Value
reportGenerator com.report.HtmlReportGenerator
reportService com.report.ReportService
reportService.reportGenerator reportGenerator
===================================================
I think this is better:
/**
*
*/
Properties configProp = new Properties();
InputStream in2 = this.getClass().getResourceAsStream(
"mail.properties");
try {
configProp.load(in2);
} catch (IOException e) {
e.printStackTrace();
}
// To get the host out of the mail.properties file, use "Host"
String host = configProp.getProperty("Host");
"mail.properties" content
Host=smtpout.secureserver.net
====================================
====================================
This explains the where and why….

There are times when it can be convenient for static files (such as text files, configuration files, images, etc.) to be packaged with a library. In the Java world, these types of files are referred to as resources and the libraries are known as jar files. The simplest way to ensure that a jar file can reference the resources it needs is to physically bundle them into the jar file itself.

The question then becomes: How can the code within a jar file reference a resource file?

Reading a Resource File

It's actually pretty simple, as illustrated in Listing 1. Java provides several ways to read a resource file, of which the simplest is to use the getResourceAsStream method provided by Java's Class class. This method accepts the name of the resource as a parameter and returns an InputStream reference for the resource (or null if it cannot find the resource). Content can be easily read from the file using a BufferedReader object.

The name provided to the getResourceAsStream method can be an absolute or relative pathname. If relative, it is interpreted relative to the package path. For example:

Type Path Expected Location
Absolute /myapp.properties /myapp.properties
Relative myapp.properties /com/keenertech/experiment/myapp.properties

The leading "/" causes the getResourceAsStream method to look for the resource at the top level within the jar file. With the relative pathname, the file is expected to be located at the same level within the jar file as the class itself.

Note that the ClassLoader class also has a getResourceAsStream method which can be used to read resources, but it only supports absolute paths. In general, the Class version of the method is more frequently used.

Listing 1 – Displaying A Resource File

package com.keenertech.experiment;
import java.io.*;
import java.util.*;
public class ResourceExperiment
{
private void displayResource(String strName)
{
try
{
BufferedReader objBin = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream(strName)));
if (objBin != null)
{
String strLine = null;
while ((strLine = objBin.readLine()) != null)
{
System.out.println(strLine);
}
objBin.close();
}
else
{
System.out.println("Error: Unable to retrieve InputStream");
}
}
catch (Exception e)
{
System.out.println(e);
}
} // End Method
public static void main(String[] args)
{
ResourceExperiment objRes = new ResourceExperiment();
objRes.displayResource("/myapp.properties");
} // End Method
} // End Class

Reading a Properties File

Well, that was a great way to read, and display, a resource file, but it would be nice to actually use the properties defined in the myapp.properties file. Listing 2 shows how the properties can easily be processed from a configuration file packaged as a resource. This technique can be a great way to set default parameters for a class.

Listing 2 – Reading Properties From a Resource File

 private void readPropertyFile(String fileName)
{
try
{
Properties objProperties = new Properties();
objProperties.load(this.getClass().getResourceAsStream(fileName));
strHostName = objProperties.getProperty("hostname");
// .....more properties as needed.....
}
catch (Exception e)
{
System.out.println("ERROR: Could not read properties file\n");
e.printStackTrace();
}
} // End Method

To read the properties from the file, create an instance of the Properties class, then call the object's Load method with an InputStream that references the resource, as shown below:

objProperties.load(this.getClass().getResourceAsStream(fileName));

To get a value for an individual property:

strHostName = objProperties.getProperty("hostname");

Conclusion

In Java, static resources can safely and effectively be bundled with compiled classes within easily distributable jar files. Storing such resources within the jar files ensures that the resources will be available to classes when needed, i.e. — it is very difficult for the resources to become separated from the code when they are bundled with it. In turn, resources can be easily referenced by Java code, so there's no penalty, in terms of access cost, in bundling resources within jar files.