Problem:
How to load Properties in Java? Properties class has methods to load properties from different sources – InputStream, Reader, and XML file. Here’s an example of Properties.load(InputStream).
Solution:
java.util.Properties has three methods to load Properties from files:
- void load(InputStream inStream)
Reads property list (key=value pairs) from given InputStream - void load(Reader reader)
Reads property list (key=value paris) from given Reader - void loadFromXML(InputStream in)
Loads all properties from XML document in format as produced by Properties.storeToXML() method.
In the following example we show how to use Properties.load(InputStream) to load a app-config.properties:
package com.farenda.java.util; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; public class PropertiesLoad { public static void main(String[] args) throws IOException { Properties config = loadFromFile("app-config.properties"); printToSystemOutput(config); } private static void printToSystemOutput(Properties config) throws IOException { config.store(System.out, "Loaded properties:"); } private static Properties loadFromFile(String filename) throws IOException { Path configLocation = Paths.get(filename); System.out.println("Config location: " + configLocation.toString()); try (InputStream stream = Files.newInputStream(configLocation)) { Properties config = new Properties(); config.load(stream); return config; } } }
Put the following content in app-config.properties and place it in your projects directory (or src/main/resources if you are using Maven or Gradle):
database=localhost:2017 username=user password=secretpassword
Running the code produces the following output:
Config location: app-config.properties #Loaded properties: #Sun Sep 06 17:53:59 CEST 2015 password=secretpassword database=localhost\:2017 username=user
The code for Properties.load(Reader) is the same. You just need to create a Reader instead of InputStream.