任何編程語言都有自己的讀寫配置文件的方法和格式,Java也不例外。
在Java編程語言中讀寫資源文件最重要的類是Properties,功能大致如下:
1. 讀寫Properties文件
2. 讀寫XML文件
3. 不僅可以讀寫上述兩類文件,還可以讀寫其它格式文件如txt等,只要符合key=value格式即可.
注意:資源文件中含有中文時的處理方法
1. 將中文字符通過工作轉成utf8編碼,可以通過Java自帶的nativetoascii或Eclipse中的屬性編輯器。
2. 直接調用 new String(youChineseString.getBytes("ISO-8859-1"), "GBK");
附:WEB程序中加載資源文件的方法
Properties prop = null;
1. prop = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename");
2. prop = this.getClass().getClassLoader().getResourceAsStream("filename");
Properties類繼承自Hashtable,大致API如下:
好了,直接用代碼說話吧,這個類很容易使用
看下Demo目錄結構:
先來個讀取配置文件類:PropertiesReader.java
關於Properties讀取文件這里提供六種方法:《
JAVA讀取Properties的六種方法》,下面取最常用的一種
關於路徑的寫法:(可以相對路徑也可以是絕對路徑)
Class.getResourceAsStream(String path)
path 不以’/'開頭時默認是從此類所在的包下取資源,以’/'開頭則是從ClassPath(src文件)根下獲取。
path 不以’/'開頭時默認是從此類所在的包下取資源,以’/'開頭則是從ClassPath(src文件)根下獲取。
1 package com.lcw.properties.test; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Enumeration; 6 import java.util.Properties; 7 8 /** 9 * properties文件讀取類 10 * 11 */ 12 public class PropertiesReader { 13 14 public void getPropertiesReader(){ 15 Properties properties=new Properties();//獲取Properties實例 16 InputStream inStream=getClass().getResourceAsStream("config.properties");//獲取配置文件輸入流 17 try { 18 properties.load(inStream);//載入輸入流 19 Enumeration enumeration=properties.propertyNames();//取得配置文件里所有的key值 20 while(enumeration.hasMoreElements()){ 21 String key=(String) enumeration.nextElement(); 22 System.out.println("配置文件里的key值:"+key+"=====>配置文件里的value值:"+properties.getProperty(key));//輸出key值 23 } 24 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 30 }
再來個測試類:PropertiesTest.java
1 package com.lcw.properties.test; 2 3 public class PropertiesTest { 4 5 /** 6 * 測試類 7 */ 8 public static void main(String[] args) { 9 PropertiesReader propertiesReader=new PropertiesReader(); 10 propertiesReader.getPropertiesReader(); 11 } 12 13 }
這是配置文件信息:config.properties
color=black animal=rabbit food=hamburger chinese=\u6211\u662F\u4E2D\u6587
看下運行效果:
若要寫入配置i文件也很簡單,這里添加一個方法:
1 //寫入資源文件信息 2 public void writeProperties(){ 3 Properties properties=new Properties(); 4 try { 5 OutputStream outputStream=new FileOutputStream("config.properties"); 6 properties.setProperty("number", "2015"); 7 properties.setProperty("song", "手寫的從前"); 8 properties.store(outputStream, "rabbit"); 9 outputStream.close(); 10 } catch (FileNotFoundException e) { 11 e.printStackTrace(); 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } 15 }
生成文件:
#rabbit #Wed Jan 07 17:16:56 CST 2015 number=2015 song=\u6211\u7231\u4F60
