1. 程式人生 > >避免緩存,Java動態加載配置文件

避免緩存,Java動態加載配置文件

避免 utf can tle == 文件的 coder txt col

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. public class FileTest {
  9. public static void main(String[] args) throws IOException {
  10. Properties prop=new Properties();
  11. String path
    =null;
  12. System.out.println(new File("").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 = new Scanner(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 = new FileInputStream(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


可以動態的進行輸入輸出的哦



null

避免緩存,Java動態加載配置文件