Java工具類--讀取Properties檔案
阿新 • • 發佈:2018-11-27
package com.skr.mdm.util; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.io.InputStreamReader; import java.util.*; /** * 讀取配置檔案的工具類 */ public class PropertiesUtil { private Properties props; public PropertiesUtil(String fileName) { readProperties(fileName); } /** * 載入配置檔案 * * @param fileName */ private void readProperties(String fileName) { try { props = new Properties(); InputStreamReader inputStream = new InputStreamReader( this.getClass().getClassLoader().getResourceAsStream(fileName), "UTF-8"); props.load(inputStream); } catch (Exception e) { e.printStackTrace(); } } /** * 根據key讀取對應的value * * @param key * @return */ public String get(String key) { return props.getProperty(key); } /** * 得到所有的配置資訊 * * @return */ public Map<String, String> getAll() { Map<String, String> map = new HashMap<String, String>(); Enumeration<?> enu = props.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); String value = props.getProperty(key); map.put(key, value); } return map; } /** * 得到所有的配置資訊 * * @return */ public List<String> keyList() { List<String> keyList = new ArrayList<>() ; Enumeration<?> enu = props.propertyNames(); while (enu.hasMoreElements()) keyList.add((String) enu.nextElement()) ; return keyList; } public static void main(String[] args) { PropertiesUtil propertiesUtil = new PropertiesUtil("MDMTag.properties") ; System.out.println(JSONObject.fromObject(propertiesUtil.getAll())) ; System.out.println(JSONArray.fromObject(propertiesUtil.keyList())) ; } }
轉至:https://blog.csdn.net/frankcheng5143/article/details/50432820?locationNum=10