在程序开发和设计中,我们经常把一些需要改变的数值配置在文件中,方便手动的去修改数据,如果写死在java程序中,并不方便维护和先关参数的修改。在文件中存储数据,直接使用a=b这样的方式存储即可。下面是读取并解析文件的方法。
package com.jhinno.appportal.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class ConfigUtil { private static ConfigUtil instance = new ConfigUtil(); private Logger logger = LogManager.getLogger(ConfigUtil.class); private Map<String,Properties> configMappings; public static final String FILE_PATH = System.getenv("FILEPATH") + File.separator + "file.conf"; private ConfigUtil(){ configMappings = new HashMap<String,Properties>(); } public static ConfigUtil getInstance(){ if(instance == null){ instance = new ConfigUtil(); } return instance; } public String getConfigByKey(String filename, String key){ Properties p = null; String value = null; if(configMappings.containsKey(filename)){ p = configMappings.get(filename); value = p.getProperty(key); }else{ p = loadProperties(filename); value = p.getProperty(key); configMappings.put(filename, p); } return value; } public Map<String, Properties> getConfigMappings() { return configMappings; } public void setConfigMappings(Map<String, Properties> configMappings) { this.configMappings = configMappings; } private Properties loadProperties(String filename){ Properties p = new Properties(); FileInputStream is = null; try { is = new FileInputStream(new File(filename)); p.load(is); is.close(); } catch (IOException e) { logger.error("ERROR:",e); try { is.close(); } catch (IOException e1) { logger.error("ERROR:",e1); } } return p; } }