如何使用排序键将java.util.Properties写入XML?

use*_*084 13 java xml

我想将属性文件存储为XML.有没有办法在执行此操作时对键进行排序,以便生成的XML文件按字母顺序排列?

String propFile = "/path/to/file";
Properties props = new Properties();
/*set some properties here*/
try {
    FileOutputStream xmlStream = new FileOutputStream(propFile);
    /*this comes out unsorted*/
    props.storeToXML(xmlStream,"");
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

eri*_*son 27

这是一个快速而肮脏的方法:

String propFile = "/path/to/file";
Properties props = new Properties();

/* Set some properties here */

Properties tmp = new Properties() {
  @Override
  public Set<Object> keySet() {
    return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
  }
};

tmp.putAll(props);

try {
    FileOutputStream xmlStream = new FileOutputStream(propFile);
    /* This comes out SORTED! */
    tmp.storeToXML(xmlStream,"");
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

以下是警告:

  • tmp属性(匿名子类)不符合属性的约定.

例如,如果你得到它keySet并试图从中删除一个元素,则会引发异常.所以,不要让这个子类的实例逃脱!在上面的代码片段中,您永远不会将其传递给另一个对象或将其返回给具有合法期望它履行属性合同的调用者,因此它是安全的.

  • Properties.storeToXML的实现可能会更改,导致它忽略keySet方法.

例如,未来版本或OpenJDK可以使用替代keys()方法.这就是为什么类应该始终记录它们的"自用"(Effective Java Item 15)的原因之一.但是,在这种情况下,最糟糕的情况是您的输出将恢复为未排序.HashtablekeySet

  • 请记住,属性存储方法会忽略任何"默认"条目.


小智 20

这是为store Properties.store(OutputStream out, String comments)和product生成排序输出的方法Properties.storeToXML(OutputStream os, String comment):

Properties props = new Properties() {
    @Override
    public Set<Object> keySet(){
        return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
    }

    @Override
    public synchronized Enumeration<Object> keys() {
        return Collections.enumeration(new TreeSet<Object>(super.keySet()));
    }
};
props.put("B", "Should come second");
props.put("A", "Should come first");
props.storeToXML(new FileOutputStream(new File("sortedProps.xml")), null);
props.store(new FileOutputStream(new File("sortedProps.properties")), null);
Run Code Online (Sandbox Code Playgroud)