How to read and write Properties configuration files in Java?

In Java, you can use the java.util.Properties class to read and write Properties configuration files. Here is a simple example:

Read the configuration file.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // 加载配置文件
            FileInputStream fileInputStream = new FileInputStream("config.properties");
            properties.load(fileInputStream);
            fileInputStream.close();

            // 读取配置项
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");

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

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Write to the configuration file:

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

public class PropertiesExample {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // 设置配置项
            properties.setProperty("username", "admin");
            properties.setProperty("password", "123456");

            // 保存配置文件
            FileOutputStream fileOutputStream = new FileOutputStream("config.properties");
            properties.store(fileOutputStream, null);
            fileOutputStream.close();

            System.out.println("Config file saved successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above example, assuming the configuration file is named config.properties and contains the following:

username=admin
password=123456

When reading a configuration file, use the load method of the Properties class to load the file stream and use the getProperty method to retrieve the value of the configuration item.

When writing to a configuration file, use the setProperty method of the Properties class to set the value of configuration items, and use the store method to save it to the file.

Please note that when reading and writing configuration files, IOException exceptions need to be handled. Additionally, the path to the configuration file can be adjusted according to the actual situation.

bannerAds