避免緩衝,Java動態載入設定檔

來源:互聯網
上載者:User

標籤:static   string   3ds   屬性   void   color   lin   tin   int   

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動態載入設定檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.