[英]Placing a properties file in a java project
我在理解將屬性文件放置在Java項目中的位置時遇到了一些麻煩。 我有以下項目結構。
src.
|
java
|
test.properties
|
a.java
Parameters.properties
我有以下代碼來讀取屬性文件。
Properties prop = new Properties();
try {
InputStream in = this.getClass().getResourceAsStream("Parameters.properties");
// load a properties file
prop.load(in);
// get the property value and print it out
System.out.println(prop.getProperty("hello.world"));
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("The code has failed here");
}
我的屬性文件包含以下行
hello.world=Hello World
我一直收到空指針錯誤,這使我相信它無法讀取文件,因為它尚未獲取文件。
您需要將Parameters.properties
文件放置在src
文件夾中,而不是built
或target
文件夾中。 或者,為簡單a.class
,請找到一個a.class
文件,然后將Parameters.properties
放在同一文件夾中。
built.
|
java
|
test.properties
|
a.class
Parameters.properties
因為當您使用getClass()
方法時,您將獲得具有.class
擴展名的二進制文件,並在該文件所在的文件夾中搜索資源。
1.)一種方法是--- 在任何源文件夾中添加屬性文件。 源文件夾是類路徑中包含的文件夾。 例如src / A.java創建另一個Source文件夾
在src級別並將文件放在此處
資源/ params.properties。
並且在A.java中,像這樣File file = new File(".//resources//params.properties");
2.)另一種簡單的方法是在src文件夾中添加屬性文件,然后右鍵單擊屬性文件->構建路徑->添加到類路徑。
像這樣在A.java中訪問文件...
File file = new File("params.properties");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.