Java中动态加载properties文件,而不需要重启应用的解决方法

在Java项目中,如果需要使用.properties类型的文件作为某些配置信息存放介质的时候,一般都是将.properties文件放在src目录下,代码大部分都是这样写的:

[java]  view plain copy
 
  1. Properties prop = new Properties();  
  2. InputStream is = CommonUtils.class.getClassLoader().getResourceAsStream("config.properties");//假设当前这个方法是在CommonUtils类下面  
  3. prop.load(is);  

在系统启动之后,config.properties中的key-value信息都可以获取,但是某一天,你想改变一下config.properties中的相关配置,但是又不能重启应用,你就会发现,明明已经修改了config.properties文件内容,为什么读出来的信息还是原先的?

经过google后发现,原来使用

[java]  view plain copy
 
  1. CommonUtils.class.getClassLoader().getResourceAsStream("config.properties")  

这种加载方法会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取!
既然以上方法会将文件信息缓存,那么我只要改变一下文件的输入流获取方式就行了。
改成如下方式就行了:

[java]  view plain copy
 
  1. Properties prop = new Properties();  
  2. String path = CommonUtils.class.getClassLoader().getResource("config.properties").getPath();  
  3. InputStream is = new FileInputStream(path);  
  4. prop.load(is);  

或者

[java]  view plain copy
 
  1. String dirPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();//获取config.properties文件所在的父目录  
  2. File file = new File(dirPath,"config.properties");  

猜你喜欢

转载自reeboo.iteye.com/blog/1980961