簡體   English   中英

Java 屬性文件路徑

[英]Java properties file path

我正在通過這樣的路徑讀取屬性文件:

String filePath = "src/main/resources/database.properties";

在我構建 jar 后,jar 嘗試再次在此特定路徑查找屬性文件,但失敗。 有沒有辦法在 jar 中打包屬性文件,或者有一個中性路徑(路徑適用於有或沒有構建 jar 的兩種方式)或任何其他解決方案?

“src/main/resources”中的文件會自動捆綁到 jar 文件中,這意味着無論在何處運行它們都可以在運行時使用。

如果要訪問JAR內部的文件,可以使用Java提供的方法:

// Get the resource "test.properties" inside the current package.
getClass().getResource("test.properties");
// Get the resource "test.properties" inside "src/main/resources". 
getClass().getResource("/test.properties");

如果你想要一個輸入 stream,你可以使用getResourceAsStream

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

您可以將其與Properties object 結合使用,以將資源作為屬性文件讀取:

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

Properties testProperties = new Properties();
testProperties.load(propertiesInput);

propertiesInput.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM