[英]Read from property file after restarting program
我正在嘗試將配置數據保存在config.properties
文件中。 我這樣保存我的屬性:
public static void setProperty(Parameter property) {
// set the property's value
prop.setProperty(property.getIndex(), property.getValue());
// save properties to project root folder
try {
prop.store(output, null);
} catch (IOException e) {
e.printStackTrace();
}
}
並像這樣加載它們:
public static String getProperty(String componentName) {
// get the property value
return prop.getProperty(componentName);
}
並且一切正常,但是當我重新啟動程序時,我沒有任何屬性了。 我在程序的開頭調用以下方法來加載我的屬性文件:
static String FILE = "config.properties";
static InputStream input;
static OutputStream output;
static Properties prop = new Properties();
public static void loadExistingProperties() {
try {
input = new FileInputStream(FILE);
output = new FileOutputStream(FILE);
// load properties from file
prop.load(input);
System.out.println("amount of saved properties: " + prop.size());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
有人可以告訴我為什么重啟程序后找不到屬性嗎? 是我嘗試弄錯prop
的方式嗎? 我不知道該怎么做。
在loadExistingProperties()
您為同一文件同時打開FileInputStream
和FileOutputStream
,但是您只想從該文件讀取。 調用FileOutputStream
將刪除文件的內容,然后才能讀取它。 只需刪除該行。
我相信,當您打開輸出流時,它會截斷文件的內容。
編輯:
您需要打開輸入流,在不打開輸出流的情況下讀取屬性文件的內容。
如果以后確實需要保存它們,則仍然可以在setProperty方法中打開輸出流並調用store方法。 或者,您可以在閱讀所有屬性並關閉輸入流之后打開輸出流。
請記住,store方法將再次保存所有屬性。
第一個問題是,每當修改屬性時,都會將整個屬性寫入output
輸出流。 這不是預期的工作方式。
Properties.store()
方法將存儲存儲在Properties
對象中的所有Properties
。 因此,您應該在調用store()
方法之前立即打開文件,並在緊隨其后關閉文件。
在我看來,您永遠不會關閉output
,這可能會導致寫入數據的數據仍然僅存在於內存緩存中,並且永遠不會寫入基礎文件。
只需保留如下屬性:
try (OutputStream out = new FileOutputStream("config.properties")) {
prop.store(out, null);
}
像這樣簡單地加載它們:
try (InputStream in = new FileInputStream("config.properties")) {
prop.load(in);
}
try-with-resources
塊將正確關閉流。
同樣,您不應該在每次修改屬性時都保留屬性。 常見的事情是僅在關閉程序或用戶要求您執行操作時才保存屬性/設置(例如“立即保存設置”菜單)。
我沒有看到您的Properties
類,但是在我看來,您沒有關閉輸出流也沒有刷新。 在執行prop.store(output, null);
時文件是否更改prop.store(output, null);
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.