[英]Path of properties file in java
我有一個屬性文件,它位於默認 package 和 class 中,我使用的屬性文件也在相同的默認 package 中。 如果我只使用沒有任何路徑的文件名,我會收到錯誤消息。 顯然這是不正確的,因為我應該給出某種路徑來引用 tat 文件。 我將構建應用程序,使其成為 jar 文件,那么我應該如何將路徑作為屬性文件應該在 jar 文件中提供 go 文件。 我正在使用 Netbeans IDE。
編輯
Properties pro = new Properties();
try {
pro.load(new FileInputStream("pos_config.properties"));
pro.setProperty("pos_id", "2");
pro.setProperty("shop_type", "2");
pro.store(new FileOutputStream("pos_config.properties"), null);
String pos_id = pro.getProperty("pos_id");
if(pos_id.equals("")){
pos_id="0" ;
}
global_variables.station_id = Integer.parseInt(pos_id);
String shop_type = pro.getProperty("shop_type");
if(shop_type.equals("")){
shop_type="0" ;
}
global_variables.shop_type = Integer.parseInt(shop_type);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
使用getClass().getResourceAsStream("foo.properties")
但請注意,不鼓勵使用默認的 package(以上適用於任何包)。
您的代碼不起作用,因為FileInputStream(..)
使用相對於當前用戶目錄的路徑(請參閱java.io.File
文檔)。 因此它在/home/usr/
或c:\documents and settings\usr
中查找foo.properties
。 由於您的.properties
文件位於類路徑中,因此您可以這樣讀取它 - 通過Class.getResourceAsStream(..)
方法。
正如其他人指出的那樣,如果您希望能夠從 jar 加載它,則應該從類路徑加載它而不是作為文件加載。 您需要Class.getResourceAsStream()方法或ClassLoader.getResourceAsStream()方法。 但是,使用getClass().getResourceAsStream("pos_config.properties")
是危險的,因為您使用的是相對於給定 class 解析的路徑,並且子類可能會更改解析它的位置。 因此,在 jar 中命名絕對路徑是最安全的:
getClass().getResourceAsStream("/pos_config.properties")
甚至更好的是,使用 class 文字而不是 getClass():
Foo.class.getResourceAsStream("pos_config.properties")
您是想從當前工作目錄中獲取屬性文件,還是想將其作為資源獲取? 聽起來你應該使用。
InputStream is = getClass().getResourceAsStream(filename);
properties.load(is);
從當前目錄加載文件
properties.load(new FileInputStream(filename));
我的猜測是你真正想要的是這個。
try {
Properties pro = new Properties();
pro.load(new FileInputStream("pos_config.properties"));
String pos_id = pro.getProperty("pos_id");
try {
global_variables.station_id = Integer.parseInt(pos_id);
} catch(Exception e) {
global_variables.station_id = 0;
}
String shop_type = pro.getProperty("shop_type");
try {
global_variables.shop_type = Integer.parseInt(shop_type);
} catch(Exception e) {
global_variables.shop_type = 0;
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
無論如何,我建議將所有屬性文件放在資源文件夾中。
在 Eclipse 中,您可以使用以下命令創建源文件夾:
右鍵->新建->源文件夾
我敢打賭 Netbeans 中也有類似的東西。 把你所有的財產文件放在那里。 稍后您可以使用以下代碼訪問它們:
AnyClass.class.getResource("/image.png")
因此,對於您的特定問題,您可以像這樣訪問它:
pro.load(new FileInputStream(YourClass.class.getResource("/pos_config.properties")));
在我使用的 static 方法中
ClassLoader.getSystemResourceAsStream("name.properties");
這不會編譯:
pro.load(new FileInputStream(YourClass.class.getResource("/pos_config.properties")));
正確使用:
pro.load(YourClass.class.getResourceAsStream("/pos_config.properties")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.