jar Java

java怎么读取jar包下的配置文件

小亿
178
2023-09-16 00:40:22
栏目: 编程语言

在Java中,可以使用以下代码读取JAR包中的配置文件:

import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
public static void main(String[] args) {
try {
// 读取JAR包中的配置文件
InputStream inputStream = ReadConfigFile.class.getResourceAsStream("/config.properties");
// 创建Properties对象
Properties properties = new Properties();
// 加载配置文件
properties.load(inputStream);
// 获取配置项的值
String value = properties.getProperty("key");
System.out.println("Value: " + value);
// 关闭输入流
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

上述代码中,ReadConfigFile类通过getResourceAsStream方法获取JAR包中的配置文件config.properties的输入流。然后使用Properties对象加载配置文件,并通过getProperty方法获取配置项的值。

请注意,要使用绝对路径来指定JAR包中的配置文件,即以/开头。

0
看了该问题的人还看了