因为有个需求要实现这个,特地上网看了下,好多都挺复杂的,这里我提供一种比较简单的方案,供大家参考。
首先配置文件: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());
}
}
}
打印结果