標籤: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’,這樣直接讀取會導致系統找不到檔案
直接,我三個檔案來研究:
package com.cn.test;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.net.URLDecoder;import java.util.Properties;import java.util.Scanner;public class FileTest {public static void main(String[] args) throws IOException {Properties prop=new Properties();String path=null;System.out.println(new File("").getCanonicalPath()+"\\setting.txt");//String path = Thread.currentThread().getContextClassLoader().getResource("setting.txt").getPath();if(path==null){path="./setting.txt";}FileInputStream in=null;while(true){Scanner sc = new Scanner(System.in);String s = sc.next();char c = s.charAt(0);if(c==‘0‘){break;}try {path = URLDecoder.decode(path, "UTF-8");in = new FileInputStream(path);prop.load(in);prop.list(System.out);} catch (Exception e) {e.printStackTrace();}finally{try {if(in!=null){in.close();}} catch (IOException e) {e.printStackTrace();}}}}}
那個設定檔:
A=2323333dsfds
可以動態進行輸入輸出的哦
null
避免緩衝,Java動態載入設定檔