package com.lyis.commons.util; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import org.apache.log4j.Logger; /** * 属性文件工具类 * * @author Johnson * @version Tuesday November 16th, 2010 */ public class PropUtils { private static Logger log = Logger.getLogger(PropUtils.class); /** * 资源对象集合 */ private static Map<String, ResourceBundle> resource = new HashMap<String, ResourceBundle>();; /** * 默认资源文件 */ private static final String DEFAULT_FILE = "conf/system"; /** * 根据文件名获取资源对象 * * @param fileName * 文件名称(相对路径) * @return */ private static ResourceBundle getBundle(String fileName) { ResourceBundle bundle = resource.get(fileName); try { if (bundle == null) { bundle = ResourceBundle .getBundle(fileName, Locale.getDefault()); resource.put(fileName, bundle); } } catch (Exception e) { log.error("Access properties file error, reason: ", e); } return bundle; } /** * 获取指定键的值 * * @param key * 键 * @param fileName * 文件名称 * @return */ public static String getString(String key, String fileName) { ResourceBundle bundle = getBundle(fileName); if (bundle != null) { if (bundle.containsKey(key)) { return bundle.getString(key); } } return null; } /** * 获取指定键的值 * * @param key * 键 * @return */ public static String getString(String key) { return getString(key, DEFAULT_FILE); } /** * 获取指定文件所有的键 * * @param fileName * 文件名称 * @return */ public static List<String> getKeys(String fileName) { List<String> listKey = new ArrayList<String>(); ResourceBundle bundle = getBundle(fileName); if (bundle != null) { Enumeration<String> et = bundle.getKeys(); while (et.hasMoreElements()) { listKey.add(et.nextElement()); } } return listKey; } /** * 获取默认默认文件多有的键 * * @return */ public static List<String> getKeys() { return PropUtils.getKeys(DEFAULT_FILE); } }