In this tutorial, you will learn to read / load properties file from classpath in Java by using load method of java.util.Properties class and getResourceAsStream method of ClassLoader class

Properties are configuration String values managed as key/value pairs. java.util.Properties is extended from java.util.Hashtable, provide the following features

  • loading key/value pairs into a Properties object from a stream

  • retrieve a value from its key

  • listing the keys and their values

  • testing to see if a particular key or value is in the Properties object

  • saving the properties to a stream

What you'll need

  • JDK 8+
  • Maven 3+

Stack

  • Java
  • Properties file

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── util
│       │               ├── ApplicationProperties.java
│       │               └── Main.java
│       └── resources
│           └── application.properties
└── pom.xml

Project dependencies


How to read / load properties file

Given a properties file


The following give you an example on reading the properties file from classpath


  • The load(InputStream inStream) method of Properties class reads a property list (key and element pairs) from the input byte stream.

    IOException, IllegalArgumentException and NullPointerException will be thrown if an error occurred when reading from the input stream, if the input stream contains malformed Unicode escape sequence and if the inStream is null respectively

  • The getResourceAsStream(String name) method of ClassLoader class returns an input stream for reading the specified classpath resource or returns null if the resource could not be found

Apart from getting the properties file from classpath, you can also load from other locations directly via FileInputStream or FileReader, for example

properties.load(new FileInputStream("src/main/resources/test.properties"));
properties.load(new FileReader("src/test.properties"));

Test


Run this command and check the result in the console log

mvn clean package exec:java

Source code

https://github.com/hellokoding/hellokoding-courses/blob/master/java-examples/java-properties-file