,所以我又回到到4年後編寫Java所以請原諒所有「菜鳥」的錯誤裏面。的讀/寫屬性文件的jar文件
我需要有一個屬性文件,我可以存儲一些簡單的數據,我的應用程序。 APP數據本身不會駐留在這裏,但我會存儲信息,如文件路徑上次使用的數據存儲,其他設置等
我設法連接到其存在同一個包裏面的屬性文件作爲類文件試圖連接到它,我可以讀取文件,但我有麻煩回寫到文件。我非常確定我的代碼能夠工作(至少它不會引發任何錯誤),但是在Netbeans中運行該應用程序後,更改並未反映在文件本身中。
在上圖中可以看到有問題的mainProperties.properties文件和類試圖調用它(prefManagement.java)。因此,考慮到這一點,這裏是我的代碼加載文件:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
這工作,我可以檢查並確認一個現有的密鑰(defaultXMLPath)。
我的代碼添加到該文件是:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
正如我上面提到的,一切都運行沒有任何錯誤,我可以玩弄嘗試添加現有的密鑰,並將其拋出預期的錯誤。但是,當試圖添加新的鍵/值對時,它不會顯示在屬性文件後綴中。爲什麼?
感謝moskito-x,我想通過這一切,我發現偏好是我正在尋找和需要使用的。我很欣賞幫助,雖然 – BenW301
@ BenW301:我很高興你找到了你的路。 :-)。不用謝。 –