java讀取 *.properties檔案中所有物件
阿新 • • 發佈:2019-02-01
這裡提供解析的輔助方法
package com.cms.util; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.Properties; public final class MiscUtil { private static Map<String, String> configProperty = null; private static String configPropertyPath="classpath:jdbc.properties"; /** * 從application.properties 檔案中有key獲取values * @param key * @return */ public static String getConfigByKey(String key) { if(isEmptyString(key)){ return null; } try{ if(configProperty==null){ configProperty= MiscUtil.convertPropertiesFileToMap(configPropertyPath); } } catch(Exception e){ //TODO add log info e.printStackTrace(); } return configProperty.get(key).trim(); } public static boolean isEmptyString(String value){ return value==null?true:(value.trim().length()<1?true:false); } public static Map<String, String> convertPropertiesFileToMap(String path) throws Exception{ InputStream input = null; Map<String,String> propertiesMap = null; try{ if(path.toLowerCase().startsWith("classpath:")){ String fileName = path.substring("classpath:".length()); input = MiscUtil.class.getClassLoader().getResourceAsStream(fileName); if(input==null){ path=MiscUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath(); path=path.substring(0, path.lastIndexOf(File.separatorChar)+1)+fileName; } } if(input==null){ input = new FileInputStream(path); } Properties properties = new Properties(); properties.load(new InputStreamReader(input, "UTF-8")); propertiesMap = new HashMap<String,String>(); for(String name : properties.stringPropertyNames()){ propertiesMap.put(name, properties.getProperty(name)); } }finally{ if(input!=null){ input.close(); } } return propertiesMap; } }
程式碼中 properties.load(new InputStreamReader(input, "UTF-8")); 這裡是設定內容格式防止中文亂碼的情況
下面給新手一點技巧 如果想要直接看到中文的話要把該檔案的格式設定為utf-8 則可以看到中文
下圖是 UNicode 碼 該檔案的格式為 iso-8859-1