First, obtain an InputStream
from which the properties are to be loaded. This can come from a number of locations, including some of the most likely:
- A
FileInputStream
, created with a file name that is hard-coded or specified via a system property. The name could be relative (to the current working directory of the Java process) or absolute.
- A resource file (a file on the classpath), obtained through a call to
getResourceAsStream
on the Class
(relative to the class file) or ClassLoader
(relative to the root of the class path). Note that these methods return null if the resource is missing, instead of raising an exception.
- A
URL
, which, like a file name, could be hard-coded or specified via a system property.
Then create a new Properties
object, and pass the InputStream
to its load()
method. Be sure to close the stream, regardless of any exceptions.
In a class initializer, checked exceptions like IOException
must be handled. An unchecked exception can be thrown, which will prevent the class from being initialized. That, in turn, will usually prevent your application from running at all. In many applications, it might be desirable to use default properties instead, or fallback to another source of configuration, such as prompting a use in an interactive context.
Altogether, it might look something like this:
private static final Properties config;
static {
Properties fallback = new Properties();
fallback.put("key", "default");
config = new Properties(fallback);
try {
InputStream stream = ...;
try {
config.load(stream);
}
finally {
stream.close();
}
}
catch (IOException ex) {
/* Handle exception. */
}
}