Java Properties File - java.util.Properties With Examples

Java properties file are used to store key-value pair configuration. java.util.Properties class is used to work with properties file in java.

Java Properties File – java.util.Properties

In java properties file can be a normal property file with key-value pairs or it can be an XML file also.

In this java properties file example, we will show you how to write a property file in both formats and then read properties from both the configuration files.

We will also show you how to load a properties file from the classpath and how to read all the keys from the properties file.

Java Properties File Example

When we run above java properties file example program, writePropertyFile method will write property files in both the format and it will be stored in the project root directory.

Here are the property files created from writePropertyFile method.


Notice the comments in the property file, it gets generated because we passed the comment also while writing the files. If we pass comment as null, there will be no comments in the property files.

Here is the output of the above java properties file program:

So when we just give the file name, it looks for the file in project root directory, the same place where it stores the property files. But when we try to load a property file from the classpath, it throws NullPointerException because it tries to load the file from Classpath that is src directory of the project.

So if we copy the properties file in the classes src directory, it’s able to load them and works fine.
In that case output of the readPropertyFileFromClasspath method is:

Also, notice that when we use the same Properties object to load another property file, we should clear its contents using clear() method. If we pass any key for which there is no value stored in the properties object, it returns null.

That’s all for properties file in java.

By admin

Leave a Reply

%d bloggers like this: