如何使用java.util.Properties读取配置文件?

当我们有一个使用文本文件存储配置的应用程序且该配置通常为key=value格式时,我们可以java.util.Properties用来读取该配置文件。

这是一个名为的配置文件示例app.config:

app.name=Properties Sample Code
app.version=1.0

下面的代码向您展示了如何读取配置。

package org.nhooo.example.util;

import java.io.*;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
            // 配置文件名
            String fileName = "app.config";
            ClassLoader classLoader = PropertiesExample.class.getClassLoader();

            // 确保配置文件存在
            URL res = Objects.requireNonNull(classLoader.getResource(fileName),
                "Can't find configuration file app.config");

            InputStream is = new FileInputStream(res.getFile());

            // 加载属性文件
            prop.load(is);

            // 获取app.name键的值
            System.out.println(prop.getProperty("app.name"));
            // 获取app.version键的值
            System.out.println(prop.getProperty("app.version"));

            // 获取app.vendor键的值,以及
            // 密钥不可用,返回Kode Java as
            // 默认值
            System.out.println(prop.getProperty("app.vendor","Kode Java"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

该代码段将打印以下结果:

Properties Sample Code
1.0
Kode Java