因爲Java中讀取配置文件的代碼比較固定,因此能夠將讀取配置文件的那部分功能單獨做爲一個類,之後能夠複用。爲了可以達到複用的目的,不能由配置文件中每個屬性生成一個函數去讀取,咱們須要一種通用的方法讀取屬性,即由用戶給出屬性名字(做爲方法參數)來獲取對應屬性的Value值。下面是示例代碼:java
1 import java.io.*; 2 import java.util.*; 3 4 import org.apache.commons.logging.Log; 5 import org.apache.commons.logging.LogFactory; 6 7 8 public class Configure { 9 10 // private static final Log log = LogFactory.getLog(ServerConfig.class); 11 private static Properties config = null; 12 13 public Configure() { 14 config = new Properties(); 15 } 16 17 public Configure(String filePath) { 18 config = new Properties(); 19 try { 20 ClassLoader CL = this.getClass().getClassLoader(); 21 InputStream in; 22 if (CL != null) { 23 in = CL.getResourceAsStream(filePath); 24 }else { 25 in = ClassLoader.getSystemResourceAsStream(filePath); 26 } 27 config.load(in); 28 // in.close(); 29 } catch (FileNotFoundException e) { 30 // log.error("服務器配置文件沒有找到"); 31 System.out.println("服務器配置文件沒有找到"); 32 } catch (Exception e) { 33 // log.error("服務器配置信息讀取錯誤"); 34 System.out.println("服務器配置信息讀取錯誤"); 35 } 36 } 37 38 public String getValue(String key) { 39 if (config.containsKey(key)) { 40 String value = config.getProperty(key); 41 return value; 42 }else { 43 return ""; 44 } 45 } 46 47 public int getValueInt(String key) { 48 String value = getValue(key); 49 int valueInt = 0; 50 try { 51 valueInt = Integer.parseInt(value); 52 } catch (NumberFormatException e) { 53 e.printStackTrace(); 54 return valueInt; 55 } 56 return valueInt; 57 } 58 }
單元測試:apache
@Test public void configureTest() { Configure config = new Configure("server.properties"); int port = config.getValueInt("server.port"); String ip = config.getValue("server.ip"); String sp = config.getValue("message.split"); System.out.println("port: " + port); System.out.println("ip: " + ip); System.out.println("sp: " + sp); }
配置文件以下:服務器
server.port =30000 server.ip=127.0.0.1 server.backgroundRun = false MAX_ERROR_NUM=1000 message.split=\# message.over=31 message.serverGetMessage=Yes message.wrong=No message.serverGetOver=over message.serverFindSIM=find message.serverNotFindSIM=NotFind