https://blog.csdn.net/jsudavid/article/details/10353349
在Java项目中,如果需要使用.properties类型的文件作为某些配置信息存放介质的时候,一般都是将.properties文件放在src目录下,代码大部分都是这样写的:
- Properties prop = new Properties();
- InputStream is = CommonUtils.class.getClassLoader().getResourceAsStream("config.properties");//假设当前这个方法是在CommonUtils类下面
- prop.load(is);
经过google后发现,原来使用
- CommonUtils.class.getClassLoader().getResourceAsStream("config.properties")
这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取!
既然以上方法会将文件信息缓存,那么我只要改变一下文件的输入流获取方式就行了。
改成如下方式就行了:
- Properties prop = new Properties();
- String path = CommonUtils.class.getClassLoader().getResource("config.properties").getPath();
- InputStream is = new FileInputStream(path);
- prop.load(is);
或者
- String dirPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();//获取config.properties文件所在的父目录
- File file = new File(dirPath,"config.properties");