用map进行缓存
package edu.bupt626.asc.ui.cache;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
//单例模式
public class CacheManager {
private static CacheManager cacheManager;
// key: code
private ConcurrentHashMap codeMap;
public static CacheManager getInstance(){
if(cacheManager == null){
init();
}
return cacheManager;
}
private static synchronized void init(){
if(cacheManager == null)
cacheManager = new CacheManager();
}
private CacheManager(){
codeMap = new ConcurrentHashMap();
}
public boolean addCode(String code, int state){
CodeInfo info = codeMap.get(code);
if(info == null){
codeMap.put(code, new CodeInfo(code, state, new Date()));
return true;
}
else if(info.getState() != state){
info.setState(state);
info.setTimestamp(new Date());
}
return false;
}
public CodeInfo getCode(String code){
return codeMap.get(code);
}
public Collection getCodeInfos(){
return codeMap.values();
}
public Collection getCodes(){
return codeMap.keySet();
}
public void removeCode(String code){
codeMap.remove(code);
}
}
被缓存实体类CodeInfo
package edu.bupt626.asc.ui.cache;
import java.util.Date;
public class CodeInfo {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private int state;
private Date timestamp;
CodeInfo(String code, int state, Date timestamp){
this.code = code;
this.state = state;
this.timestamp = timestamp;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
java读配置文件.properties的类
.properties文件:
key = value1
key2 = value2
package edu.bupt626.acs.ui.util;
import java.io.IOException;
import java.util.Properties;
//单例模式
public class AppContext {
private static AppContext instance;
private Properties properties;
// the name of the configuration file
public static final String CONFIG_FILE = "/server.properties";
private static synchronized void init() {
if (instance == null)
instance = new AppContext();
}
public static AppContext getInstance() {
if (instance == null)
init();
return instance;
}
private AppContext() {
// Load the property file
properties = new Properties();
try {
properties.load(AppContext.class.getResourceAsStream(CONFIG_FILE));
} catch (IOException e) {
e.printStackTrace();
}
}
public Properties getProperties() {
return properties;
}
}
当需要读取配置文件中信息时,调用即可
Properties props = AppContext.getInstance().getProperties();
String obj = props.getProperty(配置文件中的key值);