保持顺序的 Java Properties 类
根据封装好的OrderedProperties类封装
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
/**
* OrderedProperties
*/
public class OrderedProperties extends Properties {
private static final long serialVersionUID = -4627607243846121965L;
private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
public Enumeration<Object> keys() {
return Collections.<Object> enumeration(keys);
}
public Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
public Set<Object> keySet() {
return keys;
}
public Set<String> stringPropertyNames() {
Set<String> set = new LinkedHashSet<String>();
for (Object key : this.keys) {
set.add((String) key);
}
return set;
}
}
根据封装好的OrderedProperties类封装
/**
*
* @author xxh
*
*/
final public class PropertiesFile {
private static Map<String,Map<String,String>> files = new HashMap<String,Map<String,String>>();
private PropertiesFile(){}
/**
* 根据properties文件名把对应的属性值装换成map, 获取属性值直接从map中去对应的key
* @param file
* @return
* @throws ExcelException
*/
public static Map<String,String> properties2Map(String file) throws ExcelException{
Map<String,String> map = files.get(file);
if(map != null)//缓存中的map
return map;
map = new LinkedHashMap<String,String>();
System.err.println("读取配置文件-------------------"+file);
Properties props = null;
try {
props = new OrderedProperties();
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("properties_config/"+file));
} catch (IOException e) {
throw new RuntimeException("类路径properties_config下需要放置["+file+"]文件!", e);
}catch(NullPointerException e){
throw new RuntimeException("类路径properties_config下需要放置["+file+"]文件!", e);
}
for(Object key : props.keySet()){
map.put((String)key, (String)props.get(key));
}
props.clear();
files.put(file, map);
return map;
}
}