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

In this tutorial, you will learn to read properties file in Java by using load method of java.util.Properties class

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


Properties file and Handler

Properties file


Reading Properties file


  • 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 resource or returns null if the resource could not be found

  • Apart from getting the input stream from ClassLoader, you can also do it directly via FileInputStream, for example

properties.load(new FileInputStream("src/main/resources/application.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