Java Read and Write Properties file with Examples


The Properties file in Java programming is a file that is used to store key-value pair Strings that mainly contain configuration details. The extension of this file is .properties

Example: Write a .properties file in Java using Properties class

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

/**
 * Example: Write properties file. 
 */
public class WriteJavaPropertiesFile {

    public static void main(String... args) throws IOException {

        OutputStream outputStream = new FileOutputStream("config.properties");
        Properties properties = new Properties();

        //Production Environment
        properties.setProperty("prod.db.username","root");
        properties.setProperty("prod.db.password","123456");
        properties.setProperty("prod.domain","https://code2care.org");

        //UAT Environment
        properties.setProperty("uat.db.username","root");
        properties.setProperty("uat.db.password","654321");
        properties.setProperty("uat.domain","https://uat.code2care.org");

        properties.store(outputStream, "This is our prop file!");

    }
}
Writing feed properties file

Example: Read a .properties file in Java using Properties class

package org.code2care;

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

class ReadJavaPropertiesFile {

    public static void main(String... args) throws IOException {

        InputStream inputStream = new FileInputStream("config.properties");

        Properties properties = new Properties();
        properties.load(inputStream);

        System.out.println(properties.getProperty("uat.db.password"));
        System.out.println(properties.getProperty("prod.db.password"));
        System.out.println(properties.getProperty("prod.domain"));

    }
}
Output:
654321
123456
https://code2care.org
Exception:

If the file is not present, you will get FileNotFoundException,

Exception in thread "main" java.io.FileNotFoundException: configs.properties (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
	at org.code2care.ReadJavaPropertiesFile.main(ReadJavaProperties.java:10)

If a property is not found then the getProperty() returned value is null.

Get Code:
  1. ReadJavaProperties.java
  2. WriteJavaPropertiesFile.java

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap