Properties.store() – 抑制时间戳注释

是否可以强制Properties不在前面添加日期注释? 我的意思是这里的第一行:

 #Thu May 26 09:43:52 CEST 2011 main=pkg.ClientMain args=myargs 

我想完全摆脱它。 我需要我的配置文件是差异相同的,除非有一个有意义的改变。

给定源代码或属性,不,这是不可能的。 顺便说一句,因为Properties实际上是一个哈希表,因为它的键没有排序,所以你不能依赖于属性总是以相同的顺序。

如果我有这个要求,我会使用自定义算法来存储属性。 使用Properties的源代码作为启动器。

可能不会。 此时间戳在Properties上以私有方法打印,并且没有用于控制该行为的属性。

只有我想到的想法:子类Properties ,覆盖store并复制/粘贴store0方法的内容,以便不打印日期注释。

或者 – 提供一个自定义的BufferedWriter ,它可以打印除第一行之外的所有行(如果你添加真正的注释,将会失败,因为自定义注释会在时间戳之前打印…)

基于https://stackoverflow.com/a/6184414/242042,这里是我编写的实现,它删除了第一行并对键进行了排序。

 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 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); } } 

清洁看起来像这样

  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, ""); } 

当有意义的配置发生变化时,你能不能在应用程序中标记出来,只有在设置文件时才写入文件?

您可能希望查看Commons Configuration ,它在编写和读取属性文件等内容时具有更大的灵活性。 特别是,它有一些方法尝试编写与现有属性文件完全相同的属性文件(包括间距,注释等)。

如果你尝试在给xxx.conf文件中修改它将是有用的。

write方法用于跳过store方法中的第一行(#Thu May 26 09:43:52 CEST 2011)。 write方法一直运行到第一行结束。 之后它会正常运行。

 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') { // Used to go to next line if did use this line // you will get the continues output from the give file super.write('\n'); firstlineseen = true; } } } private static final long serialVersionUID = 7567765340218227372L; @Override public synchronized Enumeration 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); } }