读取property文件的Util类:
所需jar包:
编写PropertiesUtil类:
package com.west.util.property;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import java.util.Properties;import org.apache.log4j.Logger;/** * 工具类: 操作Property文件 * */public class PropertiesUtil { private static Logger logger = Logger.getLogger(PropertiesUtil.class); private static MappropertyMap = new HashMap (); private static Properties objProperties = null; private PropertiesUtil() { } /** * 通过fileName、key获取value */ public static String getValueByNameAndKey(String fileName, String key) { String rt = null; if (objProperties == null) { objProperties = gerProperties(fileName); } if (objProperties != null) { rt = objProperties.getProperty(key); } return rt; } /** * 通过property文件名:加载properties */ public synchronized static Properties gerProperties(String fileName) { Properties properties = propertyMap.get(fileName); if (properties == null) { properties = new Properties(); // 加载 InputStream in = PropertiesUtil.class.getClassLoader() .getResourceAsStream(fileName); System.out.println(in); try { properties.load(in); } catch (Exception e) { e.printStackTrace(); logger.error(e); } } return properties; }}
编写:message.properties文件
编写测试类:
package com.west.util.property;import org.junit.Test;public class PropertiesUtilTest { @Test public void test() { String value=PropertiesUtil.getValueByNameAndKey("message.properties","west"); System.out.println(value); }}