如果要对一个属性设置文件.properties文件进行操作,我们当然想到用java.util.Properties类.对于只进行属性读取,这个类已经足够好了,但需要在Properties实例改变之后调用.store()或者.save()需要重新输出的时候,这个类就只会简单的把所有的属性简单的输出,整个文件格式和属性的顺序都改变了,原来的注释也消失了.
附件中是一个改进过的properites文件读写类,在java.util.Properties的基础上进行改进,在读取properties文件的时候把注释和顺序格式都记录下来,操作时候也把添加顺序记录了,所以很好的解决了java.util.Properties类在输出的不足,同时它提供addComment()方法,可以添加注释,这样,经过处理的properties的可读性就能继续保持下来了.
看下面的示范代码:
FileInputStream input = new FileInputStream("e:/input.properties");
SafeProperties safeProp = new SafeProperties();
safeProp.load(input);
input.close();
safeProp.addComment("New Comment");
safeProp.put("New-Key", "New====Value");
FileOutputStream output = new FileOutputStream("e:/output.properties");
safeProp.store(output, null);
output.close();
*****************
很感谢你的这个class,我正需要这样一个类来处理我的Properties文件。
不过,我在使用的时候还是发现有一个问题,就是如果重新设置原有属性的值时后,程序不是在原来的位置修改属性,而是将原有属性删除,再作为新属性添加,这样属性的位置就发生了变动。稍微修改你的类就可以解决这个问题:
1、首先修改remove方法:
public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
}
2、修补putOrUpdate方法:
public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index,pe);
}
联系客服