properties文件讀取工具類
阿新 • • 發佈:2020-09-23
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 獲取properties文件 */ publicView Codeclass GetProperties { /** * 日誌記錄 */ protected final static Log log = LogFactory.getLog(GetProperties.class); /**讀取專案中的properties檔案 */ public static Map<String,String> readProperties(String fileName){ Map<String,String> result = new HashMap<String,String>(); InputStream inputStream= null; try { // 載入配置檔案 inputStream = GetProperties.class.getResourceAsStream("./../../michael/properties/"+fileName); Properties props = new Properties(); props.load(inputStream); for(Object key : props.keySet()){ result.put((String)key, props.getProperty((String)key)); }return result; } catch (Exception e) { System.err.println("..............讀取" + fileName + "錯誤"); log.error(e.getMessage()); } finally { try { if(inputStream!=null) inputStream.close(); } catch (IOException e) { } } return null; } public static Map<String,String> readProperties(File file){ Map<String,String> result = new HashMap<String,String>(); InputStream inputStream = null; try { // 載入配置檔案 inputStream = new FileInputStream(file); Properties props = new Properties(); props.load(inputStream); for(Object key : props.keySet()){ result.put((String)key, props.getProperty((String)key)); } } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { } } return result; } /**讀取tomcat中的properties檔案 */ public static Map<String,String> readTomcatBinProperties(String fileName){ Map<String,String> result = new HashMap<String,String>(); InputStream inputStream = null; try { // 載入配置檔案 inputStream = new FileInputStream(new File(".").getPath() + File.separator + fileName); Properties props = new Properties(); props.load(inputStream); for(Object key : props.keySet()){ result.put((String)key, props.getProperty((String)key)); } return result; } catch (Exception e) { System.err.println("..............讀取" + fileName + "錯誤"); log.error(e.getMessage()); } finally { try { if(inputStream!=null) inputStream.close(); } catch (IOException e) { } } return null; } }