我的属性文件有如下属性:
#property1=
property2=asd
是否有一个正确的方法来取消评论和改变property1?我在看Apache Commons,但似乎没有不难看的方法来做到这一点。下面的代码不起作用,因为被注释掉的属性一开始就不会被读取。
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(new File(filePath))));
config.setProperty("#property1", "new_value");
FileWriter propsFile = new FileWriter(filePath, false);
layout.save(propsFile);
我认为您正在寻找一种方法来做这个代码,而不是用编辑器。
如果您在属性文件中读取到java.util。属性,注释都丢失了。
最好的办法是将属性文件读入String,然后使用正则表达式替换更新字符串。
String newProperties = properties.replaceAll("^#*s*property1=", "property1=");
Properties props = new Properties();
props.load(new StringReader(newProperties));
扩展@garnulf所说的,您想要做config.setProperty("property1", "new_value");
您不是"取消注释"属性值,而是在运行时将属性添加到配置中。
您的配置在您第一次加载它时将不包含注释掉属性(因为它被注释掉了)。当您调用config.setProperty
时,它将被添加到您的配置