是否可以强制Properties不在前面添加日期评论?我的意思是像这里的第一行:
#Thu May 26 09:43:52 CEST 2011
main=pkg.ClientMain
args=myargs
Run Code Online (Sandbox Code Playgroud)
我想完全摆脱它.我需要我的配置文件是差异相同的,除非有一个有意义的改变.
And*_*s_D 10
可能不会.此时间戳以私有方法Properties打印,并且没有属性可以控制该行为.
只有我想到的想法:子类Properties,覆盖store和复制/粘贴store0方法的内容,以便不打印日期注释.
或者 -提供自定义BufferedWriter,打印所有但第一行(如果增加实际的意见,因为自定义的注释时间戳之前打印将失败...)
JB *_*zet 10
鉴于源代码或属性,不,这是不可能的.顺便说一句,因为Properties实际上是一个哈希表,因为它的键没有排序,所以你不能依赖于属性总是以相同的顺序.
如果我有这个要求,我会使用自定义算法来存储属性.使用Properties的源代码作为启动器.
基于/sf/answers/432909011/,这里是我编写的实现,它删除了第一行并对键进行了排序.
public class CleanProperties extends Properties {
private static class StripFirstLineStream extends FilterOutputStream {
private boolean firstlineseen = false;
public StripFirstLineStream(final OutputStream out) {
super(out);
}
@Override
public void write(final int b) throws IOException {
if (firstlineseen) {
super.write(b);
} else if (b == '\n') {
firstlineseen = true;
}
}
}
private static final long serialVersionUID = 7567765340218227372L;
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<>(super.keySet()));
}
@Override
public void store(final OutputStream out, final String comments) throws IOException {
super.store(new StripFirstLineStream(out), null);
}
}
Run Code Online (Sandbox Code Playgroud)
清洁看起来像这样
final Properties props = new CleanProperties();
try (final Reader inStream = Files.newBufferedReader(file, Charset.forName("ISO-8859-1"))) {
props.load(inStream);
} catch (final MalformedInputException mie) {
throw new IOException("Malformed on " + file, mie);
}
if (props.isEmpty()) {
Files.delete(file);
return;
}
try (final OutputStream os = Files.newOutputStream(file)) {
props.store(os, "");
}
Run Code Online (Sandbox Code Playgroud)