How to Add a Config File to a Java Project

Sybernix
2 min readNov 22, 2021

While working on some Java project, it is often the case that we need to store some values in a config file. Values such as passwords, keys, and secrets, or even some configurable properties should not be hardcoded into our Java code. In this short blog, we will see how we can read from a config file and print a config value.

You need to create a simple Java project first. Then let’s create a file named config.properties in your desired location with the following content

DB_USER=niru
DB_PASSWORD=niru

Then inside the main function of a Java class you can use the following lines of code to read the config file. You need to change the configFilePath to the actual location of the file you created above.

String configFilePath = "src/config.properties";
FileInputStream propsInput = new FileInputStream(configFilePath);

Then we need to initialize java.util.Properties and load the input file into the properties object.

Properties prop = new Properties();
prop.load(propsInput);

Now, we can read the configs from our file as follows,

System.out.println(prop.getProperty("DB_USER"));

The complete Java class is as follows,

import java.io.*;
import java.util.Properties;

public class DBHandlertest {

public static void main(String[] args) {
try {
String configFilePath = "src/config.properties";
FileInputStream propsInput = new FileInputStream(configFilePath);
Properties prop = new Properties();
prop.load(propsInput);

System.out.println(prop.getProperty("DB_USER"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

If you run this class, you will get an output as follows.

niruProcess finished with exit code 0

Voila! Now we know how to add a config file to a Java project!

--

--