How to read properties file in java

We can read a properties file in Java using the Properties class. By using an InputStream, we can load the properties file into a Properties object. If the InputStream is not null, the properties can be loaded successfully, and individual values can then be retrieved using the getProperty() method.

Below is an example program that demonstrates how to read configuration values from a properties file.

Example properties file

config.properties (place it in src/main/resources)

url=jdbc:mysql://localhost:3306/test
username=root
password=secret

Java code

import java.io.InputStream;
import java.util.Properties;
import org.testng.annotations.Test;

public class ReadProperties {

@Test
public void readProperties() {
Properties properties=new Properties();
String fileName=”config.properties”;

try(InputStream input=ReadProperties.class.getClassLoader().getResourceAsStream(fileName)){
if(input==null){
throw new RuntimeException(fileName+” not found”);
}
properties.load(input);
}

String url=properties.getProperty(“url”);
String user=properties.getProperty(“userName”);
String password=properties.getProperty(“password”);

System.out.println(url);
System.out.println(user);
System.out.println(password);
}
}

Explanation:

In the example code, a class named ReadProperties is created, and the readProperties method is executed using the @Test annotation. Inside the readProperties method, a Properties object named properties is initialized, and the variable fileName is assigned the value config.properties.

Using an InputStream, the application reads the config.properties file from the resources directory. This is done using the following method:

ReadProperties.class
    .getClassLoader()
    .getResourceAsStream(fileName)

Here, ReadProperties is the class name. By calling getClassLoader(), the class loader responsible for loading this class is obtained. The getResourceAsStream() method then loads the config.properties file from the classpath (resources folder) as an input stream.

If the input stream is not null, the properties file is successfully loaded, and the key–value pairs are read using the getProperty() method.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x