困扰很久的问题,最近学习设计模式时好好看了一下实现过程,自己简单些了一个工具类,记录一下,以后万一会用到呢。
/**
* @ClassName: Config
* @Description: properties文件获取类
* @Author: lxd
* @Date: 2021/6/7 17:11
*/
public class Config {
private static Properties properties; // 文件对象
private static Config instance; // 实例
/**
* 私有构造方法
*/
private Config(){
properties = new Properties();
// 获取类的字节码、类加载器、流文件
InputStream in = Config.class.getClassLoader().getResourceAsStream("bean.properties");
try {
// 读取流文件
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 实例类获取方法
* @return Config
*/
public static Config getInstance(){
if(instance == null){
synchronized(Config.class){
if(instance == null){
instance = new Config();
}
}
}
return instance;
}
public Properties getProperties(){
return properties;
}
public static void main(String[] args) {
Properties properties = Config.getInstance().getProperties();
String lxd = properties.getProperty("lxd");
System.out.println(lxd);
}
}
注:在运行时,properties.load(in);这块一直报空指针异常,发现文件流是空,但是在resource下确实有对应的文件名,经过调查需要在idea下指定你的resource文件为Resource Root根目录,如图:
设置之后就可以找到对应的路径了。