How can I write Java properties in a defined order?

前端 未结 5 958
粉色の甜心
粉色の甜心 2020-12-05 06:47

I\'m using java.util.Properties\'s store(Writer, String) method to store the properties. In the resulting text file, the properties are stored in a haphazard order.

5条回答
  •  半阙折子戏
    2020-12-05 07:41

    Steve McLeod's answer used to work for me, but since Java 11, it doesn't.

    The problem seemed to be EntrySet ordering, so, here you go:

    @SuppressWarnings("serial")
    private static Properties newOrderedProperties() 
    {
        return new Properties() {
            @Override public synchronized Set> entrySet() {
                return Collections.synchronizedSet(
                        super.entrySet()
                        .stream()
                        .sorted(Comparator.comparing(e -> e.getKey().toString()))
                        .collect(Collectors.toCollection(LinkedHashSet::new)));
            }
        };
    }
    

    I will warn that this is not fast by any means. It forces iteration over a LinkedHashSet which isn't ideal, but I'm open to suggestions.

提交回复
热议问题