如何利用Java的Properties类读取配置文件

Java的Properties类用于读取.properties配置文件,继承自Hashtable,支持键值对存储。1. 在src/main/resources下创建config.properties文件,包含数据库和应用配置。2. 使用ClassLoader获取资源流,通过load()方法加载配置,推荐类路径方式确保打包后可访问。3. 常用方法:getProperty()获取值,可设默认值;setProperty()设置新属性;store()保存修改。4. 注意文件位置、避免硬编码路径,敏感信息应加密。适用于中小型项目配置管理。

Java的Properties类是处理配置文件的常用工具,特别适合读取以键值对形式存储的文本文件(通常为.properties格式)。它继承自Hashtable,提供了方便的方法来加载、读取和保存配置信息。

1. 准备配置文件

在项目资源目录下创建一个名为 config.properties 的文件,内容如下:

database.url=jdbc:mysql://localhost:3306/mydb
database.username=root
database.password=123456
app.name=MyApplication
app.version=1.0

该文件定义了数据库连接和应用基本信息。

2. 使用Properties加载配置文件

通过ClassLoaderFileInputStream读取配置文件。推荐使用类路径方式,便于打包后访问。

示例代码:

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

public class ConfigReader {
    private Properties props = new Properties();

    public void loadConfig() {
        // 使用类加载器读取资源文件
        try (InputStream input = getClass().getClassLoader()
                .getResourceAsStream("config.properties")) {

            if (input == null) {
                System.out.println("无法找到配置文件!");
                return;
            }

            // 加载配置文件
            props.load(input);
            System.out.println("配置文件加载成功!");

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

    public String getProperty(String key) {
        return props.getProperty(key);
    }

    public static void main(String[] args) {
        ConfigReader reader = new ConfigReader();
        reader.loadConfig();

        // 读取配置项
        System.out.println("数据库地址: " + reader.getProperty("database.url"));
        System.out.println("用户名: " + reader.getProperty("database.username"));
        System.out.println("应用名称: " + reader.getProperty("app.name"));
    }
}

3. 常用方法说明

  • load(InputStream inStream):从输入流加载属性键值对。
  • getProperty(String key):获取指定键的值,如果不存在返回null
  • getProperty(String key, String defaultValue):获取键值,若不存在则返回默认值。
  • setProperty(String key, String value):设置新的键值对。
  • store(OutputStream out, String comment):将属性保存到文件,可用于写回配置。

4. 注意事项

确保config.properties文件位于src/main/resources(Maven/Gradle项目)目录下,这样才能被正确加载。避免硬编码文件路径,使用类路径加载更稳定。

读取敏感信息

如密码时,考虑加密处理,不要明文存储。

基本上就这些,Properties类简单易用,适合中小型项目的配置管理。