java - 属性顺序到属性文件 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
解决方案
考虑使用另一种映射来存储这些属性。最简单的方法是基于已经存在的Properties
对象创建它。
您没有提到是要保留插入顺序还是要保持所谓的自然排序。根据具体情况,您可能希望使用LinkedHashMap或TreeMap。
但是,您现在必须自己将对象输出到文件中,例如:
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()));
}
}
推荐阅读
- scala - 在scala中,如果案例类在家庭外部类型中声明,如何调用它的通用复制函数?
- php - 如何使文件在 laravel 中可下载?
- c - 函数返回时文件是否在 c 中关闭?
- python - 如何在 Anaconda 中安装 PyQt6?
- r - 如何将重复的行与缺少的字段结合起来R
- exception - 工作表中的 AVPlayer:“CALayer 位置包含 NaN:[nan nan]”(包括 MRE)
- r - 无法分配给不存在的列——使用 ARTool 包
- python - 返回 n 叉树中从根到叶的所有路径
- artificial-intelligence - 使用 Amazon 人脸识别 NodeJS 找到最合适的图像
- java - Java 程序在调用 Thread#join() 方法时冻结