温馨提示×

java怎么读取config目录下配置文件

小亿
134
2023-09-20 16:40:40
栏目: 编程语言

要读取config目录下的配置文件,可以使用Java中的Properties类来实现。

首先,需要通过类加载器获取到配置文件的输入流。假设配置文件的名字是config.properties,可以使用以下代码获取到输入流:

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");

接下来,可以使用Properties类加载输入流,并读取配置文件中的内容:

Properties properties = new Properties();
properties.load(inputStream);

现在,配置文件中的内容已经加载到Properties对象中了。可以通过getProperty()方法来获取配置项的值:

String configValue = properties.getProperty("config.key");

其中,config.key是配置项的键值。

完整的代码示例:

import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
try {
// 获取配置文件的输入流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
// 加载配置文件
Properties properties = new Properties();
properties.load(inputStream);
// 读取配置项的值
String configValue = properties.getProperty("config.key");
System.out.println("配置项的值是:" + configValue);
// 关闭输入流
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

请确保配置文件config.properties位于config目录下,并且在类路径中可访问到。

0