溫馨提示×

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

小億
267
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女