温馨提示×

java怎么读取config中的配置文件

小亿
95
2023-10-31 10:07:52
栏目: 编程语言

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

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

public class ReadConfigFile {
    public static void main(String[] args) {
        Properties properties = new Properties();
        FileInputStream fis = null;

        try {
            // 加载配置文件
            fis = new FileInputStream("config.properties");
            properties.load(fis);

            // 读取配置项的值
            String value1 = properties.getProperty("key1");
            String value2 = properties.getProperty("key2");

            System.out.println("key1 = " + value1);
            System.out.println("key2 = " + value2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

上述代码假设配置文件名为config.properties,文件内容如下:

key1=value1
key2=value2

在文件所在的目录下执行上述代码,就可以读取配置文件中的值了。

0