Java小技巧:避免缓存,Java动态加载配置文件

Java动态加载配置文件

 
关键:每次读取都要重新生成流
 
今天无意间在项目的代码中看到如下这样一段简单加载配置文件的代码:
 
Properties prop = new Properties();
InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("/config.properties");
prop.load(in);
 
 
其实代码本身是没有什么问题的
 
问题就是用这种方式来读取配置文件,会存在属性文件的缓存问题
 
什么意思呢?就是当系统在运行过程中第一次执行这段代码的时候,会将config.properties这个配置文件的信息保存在缓存当中,进而再次执行该段代码时候会从缓存当中读取,而不是再次读取config.properties配置文件
 
换句话来讲,当系统在运行时,我们去修改配置文件的相应信息,此时配置文件不会立即生效除非重启系统程序
 
所以这样操作比较繁琐,尤其是在配置文件修改频繁的情况下。所以让Java动态的加载配置文件是很有必要的
 
以下是我粗糙修改后动态加载配置文件的代码:
 
Properties prop = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("config.properties").getPath();
path = URLDecoder.decode(path, "UTF-8");
FileInputStream in = new FileInputStream(path);
prop.load(in);
 
用这种方法来获取配置文件的绝对路径,再以流的形式读取配置文件传入,避免了上述配置文件缓存的问题,能实现配置文件的动态加载。我们在程序运行的过程当中修改配置文件相应信息,程序再次执行会直接读取生效。
 
path = URLDecoder.decode(path, "UTF-8");
 
至于上面这句代码,是我后来添加的,主要是用来转换文件路径,避免空格的问题。若不用这句代码对路径进行转换,获取的文件路径当中会包含空格,且路径的空格会被替代为‘%20’,这样直接读取会导致系统找不到文件
 
 
 
直接,我三个文件来研究:
  1. package com.cn.test;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.net.URLDecoder;
  6. import java.util.Properties;
  7. import java.util.Scanner;
  8. publicclassFileTest{
  9. publicstaticvoid main(String[] args)throwsIOException{
  10. Properties prop=newProperties();
  11. String path=null;
  12. System.out.println(newFile("").getCanonicalPath()+"\setting.txt");
  13. // String path = Thread.currentThread().getContextClassLoader().getResource("setting.txt").getPath();
  14. if(path==null)
  15. {
  16. path="./setting.txt";
  17. }
  18. FileInputStream in=null;
  19. while(true){
  20. Scanner sc =newScanner(System.in);
  21. String s = sc.next();
  22. char c = s.charAt(0);
  23. if(c=='0')
  24. {
  25. break;
  26. }
  27. try{
  28. path =URLDecoder.decode(path,"UTF-8");
  29. in =newFileInputStream(path);
  30. prop.load(in);
  31. prop.list(System.out);
  32. }catch(Exception e){
  33. e.printStackTrace();
  34. }finally{
  35. try{
  36. if(in!=null){
  37. in.close();
  38. }
  39. }catch(IOException e){
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. }
  45. }
 
那个配置文件:
  1. A=2323333dsfds
 
 
可以动态的进行输入输出的哦



原文地址:https://www.cnblogs.com/xujintao/p/7587528.html