【本文介绍如何在项目中将properties文件作为参数文件,进行读取和修改,以及如何按顺序读取】
在src目录下建立test.properties文件。
public class PropertiesConfigUtil {
private volatile static Properties prop;
static {
getInstance();
}
//初始化方法
synchronized static private void getInstance() {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");
//Properties继承自Hashtabel,所以读写是无序的。若对是否有序需要求,下面可直接new一个Properties
prop = new PropertiesUtil();
try {
prop.load(in);
} catch (IOException e) {
prop = null;
e.printStackTrace();
} finally{
if(null!=in){
try {
in.close();
} catch (IOException e) {
in = null;
e.printStackTrace();
}
}
}
}
//读方法
public static String getProperty(String key){
if (null == prop) {
//使用双重检查锁
synchronized (PropertiesConfigUtil.class) {
if (null == prop) {
getInstance();
}
}
}
return prop.getProperty(key);
}
//写方法
public static void updateConfig(String key, String value){
if (null == prop) {
getInstance();
}
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
prop.setProperty(key, value);
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(path);
prop.store(outputFile, "modify");
outputFile.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputFile.close();
} catch (IOException e) {
//若流关闭时出现异常则将其设为null,保证其不占用资源
outputFile = null;
e.printStackTrace();
}
}
}
}
properties文件顺序读写关键类:
/**
* Properties文件顺序读写关键类
*/
public class PropertiesUtil extends Properties{
//由于Properties继承自Hashtabel,所以读写是无序的,现改用linkedhashset去维护则可保持顺序
private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
//重写stringPropertyNames方法,将key值存入linkedhashset维护
@Override
public Set<String> stringPropertyNames() {
Set<String> set = new LinkedHashSet<String>();
for (Object key : keys) {
set.add((String) key);
}
return set;
}
//重写keySet方法,返回的是一个linkedhashset
@Override
public Set<Object> keySet() {
return keys;
}
//重写keys方法
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(keys);
}
//重写put方法
@Override
public synchronized Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
}