Reading Data from Properties Files in Java

Properties class to simplify this process.


Step-by-Step Guide

1. Create a Properties File

Create a file named config.properties (or any name you prefer):


properties

Copy

Edit

# config.properties

username=admin

password=secret123

url=http://example.com

2. Read Properties File in Java

You can read the file using FileInputStream or InputStream (e.g., from the classpath).


Example 1: Using FileInputStream

java

Copy

Edit

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Properties;


public class PropertiesReader {

    public static void main(String[] args) {

        Properties props = new Properties();


        try (FileInputStream fis = new FileInputStream("config.properties")) {

            props.load(fis);

            String username = props.getProperty("username");

            String password = props.getProperty("password");

            String url = props.getProperty("url");


            System.out.println("Username: " + username);

            System.out.println("Password: " + password);

            System.out.println("URL: " + url);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Example 2: Reading from Classpath (e.g., inside a resources/ directory)

java

Copy

Edit

import java.io.InputStream;

import java.util.Properties;


public class ClasspathPropertiesReader {

    public static void main(String[] args) {

        Properties props = new Properties();


        try (InputStream input = ClasspathPropertiesReader.class

                .getClassLoader()

                .getResourceAsStream("config.properties")) {

            

            if (input == null) {

                System.out.println("Sorry, unable to find config.properties");

                return;

            }


            props.load(input);

            System.out.println("Username: " + props.getProperty("username"));

            System.out.println("Password: " + props.getProperty("password"));

            System.out.println("URL: " + props.getProperty("url"));

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

}

Key Points

Use Properties.load(InputStream) to load the file.

Use getProperty(String key) to read values.

Always handle exceptions like IOException.

Place the .properties file in the classpath if using class loader.

Learn Selenium JAVA Course in Hyderabad

Read More

Writing Your First Selenium Test Case Using Java

Creating Utility Classes for Common Selenium Functions

Java OOP Concepts for Selenium Testers

Working with Collections in Java for Selenium Testing

Visit Our IHUB Talent Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Handling Frames and Iframes Using Playwright

Working with Cookies and Local Storage in Playwright

Cybersecurity Internship Opportunities in Hyderabad for Freshers