因为有个需求要实现这个,特地上网看了下,好多都挺复杂的,这里我提供一种比较简单的方案,供大家参考。
首先配置文件:user.properties
zhangsan=18
lisi=24
wangwu=26
tianqi=16
初始demo
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
InputStream inputStream =
PropertiesDemo.class.getClassLoader().getResourceAsStream("user.properties");
properties.load(inputStream);
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
打印结果

可以看到输出的顺序与配置文件的顺序不一致,因为Properties继承自HashTable,不能保证存放和拿取的顺序一致。
废话不多说,由于比较简单,就直接上Demo
创建CustomProperties
public class CustomProperties extends Properties {
// 用于存放数据的集合
private Map<Object,Object> linkedHashMap = new LinkedHashMap<Object, Object>();
@Override
public synchronized Object put(Object key, Object value) {
linkedHashMap.put(key,value);
return null;
}
public Map<Object, Object> getLinkedHashMap() {
return linkedHashMap;
}
}
修改demo
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
CustomProperties properties = new CustomProperties();
InputStream inputStream =
PropertiesDemo.class.getClassLoader().getResourceAsStream("user.properties");
properties.load(inputStream);
Map<Object, Object> linkedHashMap = properties.getLinkedHashMap();
for (Map.Entry<Object, Object> entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
打印结果

本文介绍了一种使用自定义Properties类实现配置文件按插入顺序读取的方法,通过将数据存储在LinkedHashMap中,确保了读取配置文件时能保持原有的顺序。
2786

被折叠的 条评论
为什么被折叠?



