2011-08-30 44 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