首先新建properties文件url
1 public class Properties { 2 3 4 //定義配置文件名稱 5 public static final String PROPFILENAME_PROJECT = "config.properties"; 6 7 //pdf 8 public static final String URL_PDFIMAGELOG = "url.pdfImageLogo"; 9 public static final String URL_CREATEPDF = "url.toCreatePdf"; 10 public static final String URL_PDFFILE = "url.pdfFile"; 11 12 /** 13 * 根據配置文件名和key值獲取value 14 * @param fileName 15 * @param key 16 * @return 17 * @throws Exception 18 */ 19 public static String getValue(String fileName, String key) throws Exception { 20 return ReadPropertiesUtil.getValue(fileName, key); 21 } 22 /** 23 * @Description: 經過key從資源文件讀取內容,並格式化 24 * @return String 返回類型 25 * @author dongye 26 * @date 2016年6月12日 下午2:16:12 27 * @throws 28 */ 29 public static String getValue(String fileName, String key, Object[] objs) throws Exception{ 30 String pattern = getValue(fileName, key); 31 String value = MessageFormat.format(pattern, objs); 32 return value; 33 } 34 35 //默認調用project.properties配置文件 36 public static String getValue(String key) throws Exception { 37 return ReadPropertiesUtil.getValue(PROPFILENAME_PROJECT, key); 38 } 39 40 }
public class ReadPropertiesUtil { private static String propFilePath = ""; private static Map<String, Object> configMap = new HashMap<String, Object>(); public static void loadConfig(String propFilePath) throws Exception { if(PubMethod.isEmpty(configMap) || !configMap.containsKey(propFilePath)){ Properties config = new Properties(); config.load(ReadPropertiesUtil.class.getResourceAsStream(propFilePath)); configMap.put(propFilePath, config); } } /** * 經過配置文件key值,獲取對應配置值 * @param key * @return * @throws Exception */ public static String getValue(String filename,String key) throws Exception { Properties config; if (!PubMethod.isEmpty(configMap) && configMap.containsKey("/" + filename)) { config = (Properties) configMap.get("/" + filename); return config.getProperty(key).trim(); }else { loadConfig("/" + filename); config = (Properties) configMap.get("/" + filename); return config.getProperty(key).trim(); } } }