2015-10-05 21 views
4

我正在運行幾個測試,並在每次測試中寫入屬性文件。我可以成功寫入屬性文件,但每次都會更新文件,並刪除存儲在其中的以前的值。 如何寫入屬性文件而不會從文件中刪除以前的鍵值。 下面是我使用寫入屬性文件將值寫入屬性文件中的問題

public static void writeToPropertyFile(String user, String aToken) { 
    try { 
     Properties props = new Properties(); 
     props.setProperty(user, aToken); 
     FileWriter f = new FileWriter("csos.properties"); 

     props.store(f,"token"); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

我仔細觀察了一下,發現鏈接的副本爲應該完成的工作提供了很多上下文。如果我對已經存在的答案進行信用評分是不合適的,所以我將這個結果作爲一個副本來處理。 – Makoto

回答

1

一種解決方案可能是讀取文件的代碼,並把它的內容爲Properties對象。更新這個對象。然後將該對象重新寫入該文件。

像這樣:

Properties props = new Properties(); 
props.load(new FileInputStream("file.properties")); 
// work on props 
FileOutputStream output = new FileOutputStream("file.properties"); 
props.store(output, "This is overwrite file"); 

參見:Java Properties File appending new values

1

可以讀取屬性文件第一(如果存在)進行更改,然後保存。

try { 
    File file = new File("csos.properties"); 
    Properties props = new Properties(); 

    if (file.exists()) { 
     props.load(new FileReader(file)); 
    } 

    props.setProperty(user, aToken); 
    FileWriter f = new FileWriter(file); 

    props.store(f,"token"); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
}