完善资源文件工具类

This commit is contained in:
shuzheng 2016-10-18 17:31:30 +08:00
parent 4faea5d5ba
commit 15ad1b8d94
1 changed files with 44 additions and 7 deletions

View File

@ -1,26 +1,63 @@
package com.zheng.common.util;
import java.util.Date;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 配置文件读取工具
* 资源文件读取工具
*
* @author shuzheng
* @date 2016年10月15日
*/
public class PropertiesFileUtil {
// 当打开多个资源文件时缓存资源文件
private static HashMap<String, PropertiesFileUtil> configMap = new HashMap<String, PropertiesFileUtil>();
// 打开文件时间判断超时使用
private Date loadTime = null;
// 资源文件
private ResourceBundle resourceBundle = null;
// 默认资源文件名称
private static final String NAME = "config";
public PropertiesFileUtil(String bundleFile) {
resourceBundle = ResourceBundle.getBundle(bundleFile);
// 私有构造方法创建单例
private PropertiesFileUtil(String name) {
this.loadTime = new Date();
this.resourceBundle = ResourceBundle.getBundle(name);
}
public String getValue(String key) {
if (null == resourceBundle) {
return null;
public static synchronized PropertiesFileUtil getInstance() {
return getInstance(NAME);
}
return resourceBundle.getString(key);
public static synchronized PropertiesFileUtil getInstance(String name) {
PropertiesFileUtil conf = configMap.get(name);
if (null == conf) {
conf = new PropertiesFileUtil(name);
configMap.put(name, conf);
}
// 判断是否打开的资源文件是否超时1分钟
if ((new Date().getTime() - conf.getLoadTime().getTime()) > 60*1000) {
conf = new PropertiesFileUtil(name);
configMap.put(name, conf);
}
return conf;
}
// 根据key读取value
public String get(String key) {
try {
String value = resourceBundle.getString(key);
return value;
}catch (MissingResourceException e) {
return "";
}
}
public Date getLoadTime() {
return loadTime;
}
}