2011-05-19 34 views
8

當我更新屬性文件時,註釋也會沿着數據更新。有任何可能的方式來刪除註釋或更新數據而無需評論。移除屬性文件中的註釋文件java

在這裏,我更新文件4次每次日期 - 時間戳附加作爲註釋

#Thu May 19 17:53:42 GMT+05:30 2011 
Key_1=DSA_1024 
#Thu May 19 17:53:43 GMT+05:30 2011 
Key_2=DSA_1024 
#Thu May 19 17:53:43 GMT+05:30 2011 
Key_3=DSA_1024 
#Thu May 19 17:53:44 GMT+05:30 2011 
Key_4=DSA_1024 

代碼

Properties prop=new Properties(); 
      String currentDirectary=System.getProperty("user.dir"); 
      String path=currentDirectary+"/Resource/Key.Properties"; 
      FileOutputStream out=new FileOutputStream(path,true); 
      prop.setProperty("keyName","DSA_1024"); 
      prop.store(out, null); 
+1

誰添加了這些評論?你使用什麼工具。 – Bozho 2011-05-19 12:34:08

+2

向我們展示一些* update *屬性文件的代碼行 – 2011-05-19 12:35:33

+4

它看起來像您使用'Properties.store()'** **追加**到一個現有的文件,這不是它應該如何使用。您應該將所有需要的屬性添加到** one **'Properties'對象,並在該*上調用'store()'一次*。 – 2011-05-19 12:35:58

回答

1

從JavaDoc中properties.store()

如果comments參數不爲空,則會將ASCII#字符,註釋字符串和行分隔符首先寫入輸出流。因此,評論可以作爲識別評論。

接下來,註釋行總是被寫入,包含一個ASCII#字符,當前日期和時間(就像由當前時間的toString方法Date所產生的一樣)以及由Writer生成的行分隔符。

我能想到的唯一選擇是編寫自己的輸出流實現來刪除註釋。 (或者只是學會和他們住在一起:))

2

我曾經這樣做過,因爲屬性文件的使用者無法處理屬性。由store方法制造的評論被很好地定義,所以它很容易跳過它:

Writer stringOut = new StringWriter(); 
properties.store(stringOut, null); 
String string = stringOut.toString(); 
String sep = System.getProperty("line.separator"); 
out.write(string.substring(string.indexOf(sep) + sep.length())); 
1

這裏的上述其使用正確的編碼,以及黑客的改進。

FileOutputStream out = new FileOutputStream(filename); 
ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); 
props.store(arrayOut, null); 
String string = new String(arrayOut.toByteArray(), "8859_1"); 
String sep = System.getProperty("line.separator"); 
String content = string.substring(string.indexOf(sep) + sep.length()); 
out.write(content.getBytes("8859_1")); 
0

在groovy中,我寫了這個完全刪除屬性的註釋。

String writeProperties(Properties properties) { 
    def writer = new StringWriter() 
    properties.each { k, v -> 
     writer.write("${k}=${v}${System.lineSeparator()}") 
    } 
    writer.toString() 
} 

這應該很容易轉換爲普通的java。