如何使用排序键将java.util.Properties写入XML? [英] How to write java.util.Properties to XML with sorted keys?

查看:113
本文介绍了如何使用排序键将java.util.Properties写入XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order?

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


推荐答案

这是一种快速而肮脏的方式要做到这一点:

Here's a quick and dirty way to do it:

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

以下是警告:


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

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

For example, if you got its keySet and tried to remove an element from it, an exception would be raised. So, don't allow instances of this subclass to escape! In the snippet above, you are never passing it to another object or returning it to a caller who has a legitimate expectation that it fulfills the contract of Properties, so it is safe.



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

例如,未来版本或OpenJDK可以使用 Hashtable <的 keys()方法/ code>而不是 keySet 。这是类应该始终记录其自用的原因之一(Effective Java Item 15)。但是,在这种情况下,最糟糕的情况是您的输出将恢复为未排序。

For example, a future release, or OpenJDK, could use the keys() method of Hashtable instead of keySet. This is one of the reasons why classes should always document their "self-use" (Effective Java Item 15). However, in this case, the worst that would happen is that your output would revert to unsorted.


  • 请记住属性存储
    方法忽略任何默认
    条目。

这篇关于如何使用排序键将java.util.Properties写入XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆