www.un.org/spanish/ecosoc 用于java >的解决方案;8
尽管问题没有明确提及<代码>(OutputStream out, String comments)Function,但我认为这(和load(InputStream inStream)
分别属于<编码>Properties的最有趣部分。
如果我们不关心storing/loading nature<>/strong>,我们就只能取代Properties
和一些Map
或SortedMap
执行。
与<代码>Map相比,/code>上的区别在于store(>
/load(
提供一定专用序列化规则>的方法。 这些规则没有(也不会)改变各支离破碎版本。 e.g.
- Storing pairs like
prop=value
- Escaping rules for unicode and special characters.
- Adding optional comment on top
Unfortunately the above 3 parts of the functionality are hidden inside private methods, and cannot be easily re-used inside extended or alternative implementations that wish to use different internal data-structures (e.g. for keeping properties sorted).
因此,剩下的是 维护同样的内部结构,超越了两个<代码>的储存( 方法。
Note: For getting sorted properties, some time ago I followed danisupr4 implementation, but on java9 it broke.
TL;DR
The code below maintains the full functionality of Properties
by overriding only store(OutputStream out, String comments)
method, and is tested with all versions from java5
- java12
.
I believe that filtering the output of this public method makes the implementation less fragile to future code changes in java.util.Properties
class.
class SortedStoreProperties extends Properties {
@Override
public void store(OutputStream out, String comments) throws IOException {
Properties sortedProps = new Properties() {
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
/*
* Using comparator to avoid the following exception on jdk >=9:
* java.lang.ClassCastException: java.base/java.util.concurrent.ConcurrentHashMap$MapEntry cannot be cast to java.base/java.lang.Comparable
*/
Set<Map.Entry<Object, Object>> sortedSet = new TreeSet<Map.Entry<Object, Object>>(new Comparator<Map.Entry<Object, Object>>() {
@Override
public int compare(Map.Entry<Object, Object> o1, Map.Entry<Object, Object> o2) {
return o1.getKey().toString().compareTo(o2.getKey().toString());
}
}
);
sortedSet.addAll(super.entrySet());
return sortedSet;
}
@Override
public Set<Object> keySet() {
return new TreeSet<Object>(super.keySet());
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
sortedProps.putAll(this);
sortedProps.store(out, comments);
}
}
注:视何人称<代码>store()而定,最好不要凌驾于现有方法之上,而是建立新的方法:例如storeSorted(<>
。
NOTE:
For simplicity I override only one of the two store()
methods but the same concept applies to both.