【本文介绍如何在项目中将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,所以读写是无序的,现改用 edhashset去维护则可保持顺序
private final edHashSet< > keys = new edHashSet< >();
//重写stringPropertyNames方法,将key值存入 edhashset维护
@Override
public Set<String> stringPropertyNames() {
Set<String> set = new edHashSet<String>();
for ( key : keys) {
set.add((String) key);
}
return set;
}
//重写keySet方法,返回的是一个 edhashset
@Override
public Set< > keySet() {
return keys;
}
//重写keys方法
@Override
public synchronized Enumeration< > keys() {
return Collections.enumeration(keys);
}
//重写put方法
@Override
public synchronized put( key, value) {
keys.add(key);
return super.put(key, value);
}
}
继续阅读与本文标签相同的文章
-
安!排!微信聊天记录的最佳恢复方法,拿走不谢!
2026-05-19栏目: 教程
-
一线丨滴滴与清华成立未来出行联合研究中心
2026-05-19栏目: 教程
-
如何监管数字健康和人工智能产品?FDA新发布两份指南予以明确
2026-05-19栏目: 教程
-
Linux系统权限管理
2026-05-19栏目: 教程
-
滴滴与清华成立未来出行联合研究中心
2026-05-19栏目: 教程
