温馨提示×

Java怎么读写Properties配置文件

小亿
85
2024-01-19 18:15:23
栏目: 编程语言

在Java中,可以使用java.util.Properties类来读写Properties配置文件。下面是一个简单的示例:

读取配置文件:

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();
        }
    }
}

写入配置文件:

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();
        }
    }
}

上述示例中,假设配置文件名为config.properties,内容如下:

username=admin
password=123456

读取配置文件时,使用Properties类的load方法加载文件流,并使用getProperty方法获取配置项的值。

写入配置文件时,使用Properties类的setProperty方法设置配置项的值,并使用store方法保存到文件中。

请注意,读写配置文件时,需要处理IOException异常。另外,配置文件的路径可以根据实际情况进行调整。

0