在我的测试中,这个问题的其他答案在 AIX 上不能正常工作。我的特定测试机器正在运行这个版本:
IBM J9 VM(内部版本 2.4、JRE 1.6.0 IBM J9 2.4 AIX ppc64-64 jvmap6460sr9-20110624_85526
在查看了该store
方法的实现后,我发现它依赖于entrySet
. 这种方法对我很有效。
public static void saveSorted(Properties props, FileWriter fw, String comment) throws IOException {
Properties tmp = new Properties() {
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
@Override
public Set<java.util.Map.Entry<Object,Object>> entrySet() {
TreeSet<java.util.Map.Entry<Object,Object>> tmp = new TreeSet<java.util.Map.Entry<Object,Object>>(new Comparator<java.util.Map.Entry<Object,Object>>() {
@Override
public int compare(java.util.Map.Entry<Object, Object> entry1, java.util.Map.Entry<Object, Object> entry2) {
String key1 = entry1.getKey().toString();
String key2 = entry2.getKey().toString();
return key1.compareTo(key2);
}
});
tmp.addAll(super.entrySet());
return Collections.unmodifiableSet(tmp);
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
@Override
public Set<String> stringPropertyNames() {
TreeSet<String> set = new TreeSet<String>();
for(Object o : keySet()) {
set.add((String)o);
}
return set;
}
};
tmp.putAll(props);
tmp.store(fw, comment);
}