java 写文件缓存,java泛型实现文件缓存
package joyport.hbase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
/**
* 文件緩存讀寫
*
* @author xiepeng@joyport.com
*/
public class UtilFileCache {
private static String dir;
private HashMap cache = new HashMap();
/**
* 不帶最后的反斜杠
*
* @param dir
* String
* @throws Exception
*/
public UtilFileCache(String dir) throws Exception {
UtilFileCache.dir = dir;
// 檢查并創建緩存目錄
File file = new File(UtilFileCache.dir);
if (!file.exists()) {
file.mkdir();
}
}
/**
* 有內存緩存層的反持久化
*
* @param key
* String
* @return Object
* @throws Exception
*/
@SuppressWarnings("unchecked")
public T get(String key) throws Exception {
Object list = this.cache.get(key);
// 檢查有無文件緩存
if (null == list) {
list = this.readFile(key);
this.cache.put(key, list);
}
return (T) list;
}
/**
* 有內存緩存層的持久化
*
* @param key
* String
* @param data
* Object
* @throws Exception
*/
public void put(String key, T data) throws Exception {
this.cache.put(key, data);
this.saveFile(key, data);
}
/**
* 反持久化
*
* @param key
* String
* @return Object
* @throws Exception
*/
@SuppressWarnings("unchecked")
private T readFile(String key) throws Exception {
File file = new File(dir + "/" + key);
Object list = null;
if (file.exists()) {
if (file.isFile()) {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(file));
list = (Object) ois.readObject();
ois.close();
}
}
return (T) list;
}
/**
* 文件持久化
*
* @param key
* String
* @param data
* Object
* @throws Exception
*/
private void saveFile(String key, T data) throws Exception {
File file = new File(dir + "/" + key);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
file));
oos.writeObject(data);
oos.flush();
oos.close();
}
}
總結
以上是生活随笔為你收集整理的java 写文件缓存,java泛型实现文件缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: IO多路复用小故事
- 下一篇: PHP的stdClass
