@tsing1226
        
        2016-09-21T04:48:37.000000Z
        字数 1868
        阅读 1869
    标签java
import java.io.BufferedReader;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class PropertiesUtil {static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);Properties memProperties = null;static String CONFIG_FILE = "zkManager.properties";public PropertiesUtil(String confFile) {CONFIG_FILE = confFile;}/*** 通过key获取配置值* @param key* @return* @throws Exception*/public String getProperty(String key) throws Exception {return getProperty(key, null);}public String getProperty(String key, String defaultVl) throws Exception {if (null == memProperties) {logger.info("The memProperties is empty ,read properties from " + CONFIG_FILE);memProperties = loadPropertiesFromFile(null);}String value = memProperties.getProperty(key, defaultVl);if (null == value) {String info = "Cannot get valid value for the key:" + key + " from file " + CONFIG_FILE;throw new Exception(info);}return value;}/*** 读取配置文件* @param fileName:配置文件名称* @return*/protected Properties loadPropertiesFromFile(String fileName) throws Exception {if (fileName == null || fileName.isEmpty()) {fileName = CONFIG_FILE;}//获取当前路径String localPath = this.getClass().getClassLoader().getResource(".").getPath();int idx = localPath.indexOf(":") + 1;localPath = localPath.substring(idx);logger.info("loadPropertiesFromFile, the target file path : " + localPath);memProperties = new Properties();FileInputStream in = null;try {String filePathName = localPath + fileName;in = new FileInputStream(filePathName);memProperties.load(in);} catch (Exception ex) {logger.error("Error occured when reading the properties file:" + localPath, ex);throw ex;} finally {if (in != null) {try {in.close();} catch (Exception ex) {//}in = null;}}return memProperties;}public static void main(String[] args) throws Exception {PropertiesUtil propUtil = new PropertiesUtil(CONFIG_FILE);//获得配置文件中的keyname所对应的值String str = propUtil.getProperty(keyname)}}