2011-08-30 42 views
1

給定這些實例之一:org.apache.commons.configuration.PropertiesConfiguration我想寫一條評論。怎麼樣?如何向PropertiesConfiguration文件寫入註釋?

pc = new PropertiesConfiguration(); 

writeComment("this is a comment about the stuff below"); // HOW DO I WRITE THIS? 
pc.addProperty("label0", myString); 
writeComment("end of the stuff that needed a comment."); 

編輯:我有一個粗略的解決方案。希望它可以改進。


這是我能做到的最好。它在文件中留下了一個無關的行。

pc = new PropertiesConfiguration(); 
writeComment(pc, "The following needed a comment so this is a comment."); 
pc.addProperty(label0, stuff0); 
writeComment(pc, "End of the stuff that needed a comment."); 

... 
private void writeComment(PropertiesConfiguration pc, String s) 
{ 
    String propertyName = String.format("%s%d", "comment", this.commentNumber++); 

    pc.getLayout().setComment(propertyName, s + " (" + propertyName + ")"); 

    // make a dummy property 
    pc.addProperty(propertyName, "."); 
     // put in a dummy right-hand-side value so the = sign is not lonely 
} 

這種方法的問題之一是PropertiesConfiguration文檔對佈局有點模糊。它沒有明確表示註釋會出現在虛擬行上方,因此似乎存在這樣的風險,即PropertiesConfiguration可以在隨後的調用中自由地重新排列文件。我甚至沒有看到保證財產線訂單被保留,所以我不能保證評論(和虛擬行)將始終高於評論適用的財產:財產label0。當然,我在這裏有點偏執。然而,文件確實說佈局不保證不被修改。 希望有人可以拿出一些沒有虛擬行的東西,以及關於評論相對於它意在評論的屬性的評論的位置的Java文檔或網站保證。編輯:您可能想知道爲什麼我要創建一個虛擬屬性,而不是僅僅將註釋附加到文件中已有的屬性之一。原因是因爲我想要一個註釋來引入一組屬性和更改(新的或順序中的開關)是可能的。我不想製造維修問題。我的評論應該說「這是數據挖掘結果部分」或「這是時間表部分」,我不應該再訪問這個。

回答

0

這樣的評論嗎?

# This is comment 
0

的PropertiesConfiguration JavaDoc文件

Blank lines and lines starting with character '#' or '!' are skipped. 

編輯:好吧,你想要寫在代碼的註釋。也許 - 如果你只需要編寫一個屬性文件 - 您可以使用PropertiesConfiguration.PropertiesWriter及其writeComment方法是這樣的:

FileWriter writer = new FileWriter("test.properties"); 
PropertiesWriter propWriter = new PropertiesWriter(writer, ';'); 

propWriter.writeComment("Example properties"); 
propWriter.writeProperty("prop1","foo"); 
propWriter.writeProperty("prop2", "bar"); 

propWriter.close(); 

屬性文件看起來像這樣:

# Example properties 
prop1 = foo 
prop2 = bar 

更新

總結:PropertiesConfiguration不提供您正在查找的功能。

+0

我不知道如何將Java Writer對象提供給PropertiesWriter。我不知道如何從我現有的PropertiesConfiguration中獲得Java Writer。 – H2ONaCl

+0

您的解決方案似乎是使用內部類。我已經有很多使用外部類的代碼。如果有一種方法可以從外部類獲取FileWriter,那麼我就可以只使用內部類來進行註釋。然後我可以保留我的代碼的其餘部分不變。 – H2ONaCl

+0

@broiyan不幸的是,我的解決方案不適合使用外部'PropertiesConfiguration'類。我找不到任何可能性,以便在發佈財產後發表評論。對不起,我出去了! – FrVaBe