一、properties文件
Properties文件是java中很常用的一種配置文件,文件后綴為“.properties”,屬文本文件,文件的內容格式是“鍵=值”的格式,可以用“#”作為注釋,java編程中用到的地方很多,運用配置文件,可以便於java深層次的解耦。
例如java應用通過JDBC連接數據庫時,可以把數據庫的配置寫在配置文件 jdbc.properties:
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/user
user=root
password=123456
這樣我們就可以通過加載properties配置文件來連接數據庫,達到深層次的解耦目的,如果想要換成oracle或是DB2,我們只需要修改配置文件即可,不用修改任何代碼就可以更換數據庫。
二、Properties類
java中提供了配置文件的操作類Properties類(java.util.Properties):
讀取properties文件的通用方法:根據鍵得到value
/** * 讀取config.properties文件中的內容,放到Properties類中 * @param filePath 文件路徑 * @param key 配置文件中的key * @return 返回key對應的value */ public static String readConfigFiles(String filePath,String key) { Properties prop = new Properties(); try{ InputStream inputStream = new FileInputStream(filePath); prop.load(inputStream); inputStream.close(); return prop.getProperty(key); }catch (Exception e) { e.printStackTrace(); System.out.println("未找到相關配置文件"); return null; } }
把配置文件以鍵值對的形式存放到Map中:
/** * 把.properties文件中的鍵值對存放在Map中 * @param inputStream 配置文件(inputstream形式傳入) * @return 返回Map */ public Map<String, String> convertPropertityFileToMap(InputStream inputStream) { try { Properties prop = new Properties(); Map<String, String> map = new HashMap<String, String>(); if (inputStream != null) { prop.load(inputStream); Enumeration keyNames = prop.propertyNames(); while (keyNames.hasMoreElements()) { String key = (String) keyNames.nextElement(); String value = prop.getProperty(key); map.put(key, value); } return map; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } }