首页 > 解决方案 > 属性顺序到属性文件 Java

问题描述

当我执行以下代码来创建属性文件时,它不遵守顺序。

public Config() {
    this.configFile = new Properties();
    InputStream input = null;
    try {
        input = new FileInputStream("resources/config.properties");
        this.configFile.load(input);
    } catch (IOException e) {
        System.err.println("[ err. ] " + e);
    }
}

public static void initConfig() {
    if(!new File("resources/config.properties").exists()) {
        Properties prop = new Properties();
        prop.setProperty("test_key_1", "Value1");
        prop.setProperty("test_key_2", "Value2");
        prop.setProperty("test_key_3", "Value3");
        prop.setProperty("test_key_4", "Value4");
        prop.keySet();
        try {
            prop.store(new FileOutputStream("resources/config.properties"), null);
            System.out.println("[ info ] Configuration file successful created.");
        } catch (IOException e) {
            System.err.println("[ err. ] " + e);
        }
    }
}

当我打开时config.properties,我有这个:

test_key_3=Value3
test_key_2=Value2
test_key_1=Value1
test_key_4=Value4

我想要这个:

test_key_1=Value1
test_key_2=Value2
test_key_3=Value3
test_key_4=Value4

标签: javaproperties

解决方案


考虑使用另一种映射来存储这些属性。最简单的方法是基于已经存在的Properties对象创建它。

您没有提到是要保留插入顺序还是要保持所谓的自然排序。根据具体情况,您可能希望使用LinkedHashMapTreeMap

但是,您现在必须自己将对象输出到文件中,例如:

Map<Object, Object> map = new TreeMap<>(yourPropertiesObject);
try(PrintWriter printer = new PrintWriter(yourOutputFile)) {
  for (Entry<Object, Object> e : map.entrySet()) {
    printer.println(String.format("%s=%s", e.getKey(), e.getValue()));
  }
}

推荐阅读