2013-03-06 92 views
6

如何刪除屬性文件中的鍵和值?我的財產文件包含以下內容:刪除屬性文件中的條目

key1=value1 
key2=value2 

我用下面的代碼刪除條目key2=value2。在此之後,現在該文件具有以下值:

key1=value1 
key2=value2 
Wed Mar 06 12:36:32 IST 2013 
key1=value1 

Java代碼來刪除條目:

FileOutputStream out1 = new FileOutputStream(file, true); 
prop.remove(key); 
prop.store(out1,null); 

什麼是錯我做。如何在寫入文件之前清除文件的全部內容。

+0

嘗試'新的FileOutputStream中(文件,* FALSE *)' – 2013-03-06 07:19:35

+0

檢查http://stackoverflow.com/questions/4225794/delete-key-and-value-from-a-property-file – Abi 2013-03-06 07:20:44

+0

不要以追加模式打開文件。 – 2013-03-06 07:21:10

回答

7

1)屬性文件內容應該如下:

key1=value1 
key2=value2 

2)您正在打開中追加模式的文件,這是錯誤的。它應該是:

new FileOutputStream(file); 

3)關閉out1明確,Properties.store API:

輸出流保持此方法返回後開放。

如果你不想使用Properties.store,你可以寫屬性直接

PrintWriter pw = new PrintWriter("test.properties"); 
for(Entry e : props.entrySet()) { 
    pw.println(e); 
} 
pw.close(); 
+0

你得到它謝謝.. – Rachel 2013-03-06 07:21:56

+0

「prop.store(out1,null);」這是寫入屬性文件的唯一方法嗎? – Rachel 2013-03-06 10:33:12

+0

它是特別設計的保存屬性的方法,當屬性文件需要 – 2013-03-06 10:58:46