共計 664 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 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 包中的配置文件,即以 /
開頭。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-20