背景:
在写项目的时候,常常要读取配置文件中的数据,如果不进行封装,每次都要写大量重复代码,写起来很麻烦。基于这个痛点,便会想在一个类实现配置文件的读取,其他地方直接用行不行,于是想到了封装成工具类。 下面是用单例模式的饿汉式,封装一个读取、修改配置文件的类,项目中哪里需要直接用就行了,方便了许多。
配置文件:
放置在 src/test/resources 目录下
实现代码:
//饿汉式单例加载配置
public class ConfigSingleton {
static String filePath = "src/test/resources/properties";
private static Properties properties;
private static ConfigSingleton instance = new ConfigSingleton();
//获取实例
public static ConfigSingleton getInstance() {
return instance;
}
//构造方法
private ConfigSingleton(){
properties = new Properties();
try {
FileInputStream fis = new FileInputStream(filePath);
properties.load(new InputStreamReader(fis,"UTF-8"));
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//获取配置文件中的属性
public static String getKey(String key){
return properties.getProperty(key);
}
//往配置文件中添加字段和值
public static boolean setKeyValue(String key,String value){
try {
// 设置属性值
properties.setProperty(key, value);
// 将属性写回到文件中
FileOutputStream fos = new FileOutputStream(filePath);
properties.store(new OutputStreamWriter(fos,"UTF-8"), "Updated");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
//此处为具体的使用方式
//在其他地方也是这么用,先获取下单例对象,然后直接调get,set方法就可以获取,很方便
public static void main(String[] args) {
ConfigSingleton instance = ConfigSingleton.getInstance();
System.out.println("name:" + instance.getKey("name"));
//往配置文件里加字段和值
instance.setKeyValue("demo","测试一下");
System.out.println("demo:" + instance.getKey("demo"));
}
}
祝大家龙年大吉。