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<T> {
	private static String dir;
	private HashMap<String, Object> cache = new HashMap<String, Object>();

	/**
	 * 不带最后的反斜杠
	 * 
	 * @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();
	}
}

 

发表评论

电子邮件地址不会被公开。

*