如何以定义的顺序编写Java属性?
我正在使用java.util.Properties的store(Writer,String)方法来存储属性。 在生成的文本文件中,属性以偶然的顺序存储。
这就是我正在做的事情:
Properties properties = createProperties(); properties.store(new FileWriter(file), null);
如何确保按字母顺序或按属性添加顺序写出属性?
我希望解决方案比“手动创建属性文件”更简单。
根据“新白痴”的建议,这按字母顺序排列。
Properties tmp = new Properties() { @Override public synchronized Enumeration
有关完整实现的信息,请参阅https://github.com/etiennestuder/java-ordered-properties ,该实现允许以明确定义的顺序读/写属性文件。
OrderedProperties properties = new OrderedProperties(); properties.load(new FileInputStream(new File("~/some.properties")));
Steve McLeod的解决方案在尝试排除不区分大小写时并没有起作用。
这就是我提出的
Properties newProperties = new Properties() { private static final long serialVersionUID = 4112578634029874840L; @Override public synchronized Enumeration keys() { Comparator byCaseInsensitiveString = Comparator.comparing(Object::toString, String.CASE_INSENSITIVE_ORDER); Supplier> supplier = () -> new TreeSet<>(byCaseInsensitiveString); TreeSet sortedSet = super.keySet().stream() .collect(Collectors.toCollection(supplier)); return Collections.enumeration(sortedSet); } }; // propertyMap is a simple LinkedHashMap newProperties.putAll(propertyMap); File file = new File(filepath); try (FileOutputStream fileOutputStream = new FileOutputStream(file, false)) { newProperties.store(fileOutputStream, null); }