Java關於Properties用法的總結(一),javaproperties
最近項目中有一個這樣的需求,要做一個定時任務功能,定時備份資料庫的操表,將表資料寫入txt檔案。因為檔案的讀寫路徑可能需要隨時改動,所以寫死或者寫成靜態變數都不方便,就考慮使用設定檔,這裡總結些設定檔用法。
一、Java Properties類
1、Java中有個比較重要的的類Properties(java.util.Properties),是代表一個持久的一套詳細屬性,屬性可以被儲存到一個流或從流中載入的類。以下是關於屬性的要點:
-
屬性列表中每個鍵及其對應值是一個字串。
-
一個屬性列表可包含另一個屬性列表作為它的“預設”,第二個屬性可在列表中搜尋,如果沒有在原有的屬性列表中找到的屬性鍵。
-
這個類是安全執行緒的;多個線程可以共用一個Properties對象,而不需要外部同步
-
2、該類的主要方法如下:
3、主要用於讀取Java設定檔,存放一些經常用到的資料,方便程式員修改。該設定檔是個文字檔,尾碼名為(.properties),
檔案的內容格式為“key=value”,文本注釋可以使用”#“來注釋。如:
4、在設定檔中直接寫中文讀取的時候會有亂碼,所以要轉碼成ASCII。eclipse最新版本中會自動轉碼,如果需要手動轉碼,可以藉助一些線上轉碼工具,這裡推薦一個:
http://tool.oschina.net/encode?type=3
二、Java Properties執行個體
1、從目標路徑test.properites中擷取輸入資料流對象
2、使用Properties類的load()方法從位元組輸入資料流中擷取資料
3、直接列印Properties對象
4、使用Properties類的getProperty(String key)方法,根據參數key擷取value
5、具體代碼如下:
package example;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLDecoder;import java.net.URLEncoder;import java.util.Properties;public class Test { public static void main(String[] args) { try { Properties prop = new Properties(); InputStream in = Test.class.getClassLoader().getResourceAsStream( "test.properties"); prop.load(in); //直接輸出prop對象 System.out.println("直接輸出prop對象:"+prop); //擷取name的值 String name=prop.getProperty("name"); //擷取address的值 String address=prop.getProperty("address"); //擷取job的值 String job=prop.getProperty("job"); System.out.println("name="+name+",address="+address+",job="+job); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}6、執行結果如下:
從可以看出,job的值是亂碼,說明在設定檔中不可以直接使用中文。還有#號後面的注釋沒有列印出來。
三、關於路徑問題的補充
1、上述獲得Properties設定檔中英文是通過Test.class.getClassLoader().getResourceAsStream()方法直接獲得位元組輸入資料流,所以不用考慮路徑中是否包含中文的問題,如果是通過Test.class.getClassLoader().getResource()方法,因為該方法傳回值是URL,如果項目的目錄中有中文命名,則獲得的URL會出現亂碼,所以使用
String path=URLDecoder.decode(url.getFile(), "utf-8");
2、具體代碼如下:
package example;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLDecoder;import java.net.URLEncoder;import java.util.Properties;public class Test { public static void main(String[] args) { try { Properties prop = new Properties(); Properties prop2 = new Properties();// String path =Test.class.getClassLoader().getResource("example/china/test2.properties").getPath(); //獲得URL路徑 URL url=Test.class.getClassLoader().getResource("example/china/test2.properties"); //列印路徑 System.out.println("url.getFile()="+url.getFile()); //將路徑中的中文轉碼 String path=URLDecoder.decode(url.getFile(), "utf-8"); System.out.println("path="+path); //通過路徑獲得位元組輸入資料流 InputStream input=new FileInputStream(path); //直接獲得位元組輸入資料流 InputStream in = Test.class.getClassLoader().getResourceAsStream("example/china/test2.properties"); prop.load(in); prop2.load(input); System.out.println("prop="+prop); System.out.println("prop2="+prop2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
3、輸出結果: