第一章 屬性檔案操作工具類,第一章工具類
1、代碼實現
給出的屬性檔案:http.properties(位於類路徑下)
1 #每個路由的最大串連數2 httpclient.max.conn.per.route = 20 3 #最大總串連數4 httpclient.max.conn.total = 4005 #連線逾時時間(ms)6 httpclient.max.conn.timeout = 10007 #操作逾時時間(ms)8 httpclient.max.socket.timeout = 1000View Code
注意:eclipse預設的屬性編輯器不可以顯示中文,安裝外掛程式(eclipse--propedit_5.3.3)即可。
屬性檔案操作工具:FileUtil
1 package com.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; 6 7 import org.apache.commons.lang.math.NumberUtils; 8 9 /**10 * 檔案操作工具類11 */12 public class FileUtil {13 14 /**15 * 載入屬性檔案*.properties16 * @param fileName 不是屬性全路徑名稱,而是相對於類路徑的名稱17 */18 public static Properties loadProps(String fileName){19 Properties props = null;20 InputStream is = null;21 22 try {23 is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);//擷取類路徑下的fileName檔案,並且轉化為輸入資料流24 if(is != null){25 props = new Properties();26 props.load(is); //載入屬性檔案27 }28 } catch (Exception e) {29 e.printStackTrace();30 }finally{31 if(is!=null){32 try {33 is.close();34 } catch (IOException e) {35 e.printStackTrace();36 }37 }38 }39 40 return props;41 }42 43 /*44 * 這裡只是列出了從屬性檔案中擷取int型資料的方法,擷取其他類型的方法相似45 */46 public static int getInt(Properties props, String key, int defaultValue){47 int value = defaultValue;48 49 if(props.containsKey(key)){ //屬性檔案中是否包含給定索引值50 value = NumberUtils.toInt(props.getProperty(key), defaultValue);//從屬性檔案中取出給定索引值的value,並且轉換為int型51 }52 53 return value;54 }55 56 /**57 * 測試58 */59 public static void main(String[] args) {60 Properties props = FileUtil.loadProps("http.properties");61 System.out.println(FileUtil.getInt(props, "httpclient.max.conn.per.route", 10));//屬性檔案中有這個key62 System.out.println(FileUtil.getInt(props, "httpclient.max.conn.per.route2", 10));//屬性檔案中沒有這個key63 }64 }View Code
注意: