Ver Fonte

增加带排序功能的配置类,实现导出配置文件内容排序

luoshi há 2 anos atrás
pai
commit
4cfe074325

+ 1 - 1
src/main/java/com/qmth/ops/biz/utils/PropertyFileUtil.java

@@ -13,7 +13,7 @@ import java.util.Set;
 public class PropertyFileUtil {
 
     public static void write(List<PropertyItem> propertyList, OutputStream ous, String comment) throws IOException {
-        Properties p = new Properties();
+        Properties p = new SortedProperties();
         for (PropertyItem item : propertyList) {
             p.put(item.getKey(), item.getValue());
         }

+ 30 - 0
src/main/java/com/qmth/ops/biz/utils/SortedProperties.java

@@ -0,0 +1,30 @@
+package com.qmth.ops.biz.utils;
+
+import java.util.*;
+
+/**
+ * 带key排序功能的配置类
+ */
+public class SortedProperties extends 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<>(Comparator.comparing(o -> o.getKey().toString()));
+        sortedSet.addAll(super.entrySet());
+        return sortedSet;
+    }
+
+    @Override
+    public Set<Object> keySet() {
+        return new TreeSet<>(super.keySet());
+    }
+
+    @Override
+    public synchronized Enumeration<Object> keys() {
+        return Collections.enumeration(new TreeSet<>(super.keySet()));
+    }
+}