1. 程式人生 > >java讀取properties配置文件工具類

java讀取properties配置文件工具類

bstr final puts exceptio 發生 ret void err util

import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; /** * @功能描述: 獲取資源配置文件信息 * * @作者:zhangpj @創建時間:2015年12月3日 */ public final class Globals { /** *global.properties 文件 */ // 配置文件文件名 private static String fileName = "GolbalsConfig"; // 配置文件後綴名 private static String fileType = ".properties"; // 配置文件全名 private static String fullFileName = fileName+fileType; // 配置文件位置(相對路徑,WEB-INF目錄下) private static String relaPath = ""+fullFileName; // 配置文件內容 private static Properties pps = GetAllProperties(); /** * @功能描述: 獲取配置文件 * * @作者:zhangpj @創建時間:2015年12月3日 * @return */ public static Properties GetAllProperties(){ // 項目根路徑 String rootPath =Globals.class.getResource("/").toString(); rootPath = rootPath.substring(rootPath.indexOf("/")+1); // 配置文件全路徑 String filePath = rootPath+relaPath; System.out.println("配置文件路徑"+filePath); Properties properties = new Properties(); try { InputStream in = new BufferedInputStream(new FileInputStream(filePath)); properties.load(in); } catch (Exception e) { System.err.println("獲取資源配置文件["+fullFileName+"]發生錯誤!"); } return properties; } /** * 通過key名獲取global.properties的值,字符串類型 * * @param key * @return 返回字符串 */ public static String getProp(String key) { return pps.getProperty(key); } /** * 通過key名獲取global.properties的值,整數類型 * * @param key * @return 返回字符串 */ public static int getPropInt(String key) { String str = Globals.getProp(key); int rt = 0; try { rt = str == null ? 0 : Integer.parseInt(str.trim()); } catch (Exception e) { rt = 0; } return rt; } /** * 通過key名獲取global.properties的值,小數類型 * * @param key * @return 返回字符串 */ public static float getPropFloat(String key) { String str = Globals.getProp(key); float rt = 0f; try { rt = str == null ? 0f : Float.parseFloat(str.trim()); } catch (Exception e) { rt = 0f; } return rt; } public static void main(String[] args) { System.out.println(Globals.getProp("ftpIp")); System.out.println(Globals.getPropInt("ftpPort")); System.out.println(Globals.getProp("ftpUserName")); System.out.println(Globals.getProp("ftpUserPass")); System.out.println(null == Globals.getProp("shopId222")); } }

java讀取properties配置文件工具類