File缓存的进级实践

将数据缓存到file中,便于下次恢复数据,或者预先加载。java

Cache管理类: ObjectOutputStream及Serializable 的api,,自行查看 java文档android

public class CacheManager {api

public static CacheManager mInstance;

static {
	mInstance = new CacheManager();  //单例
}
private CacheManager() {
}
public <T> T readCacheFile(Context context, T t, String fileName) {
	ObjectInputStream in = null;
	try {
		File file = new File(context.getCacheDir(), fileName);
		if (!file.exists()) {
			return null;
		}
                                           //下步操做,也能够用android 中context对象来获取 流
		FileInputStream file_in = new FileInputStream(file);
		in = new ObjectInputStream(file_in);
		t = (T) in.readObject();
		return t;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	} finally {
		if (in != null) {
			try {
				in.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}
	}

}

/*
 * mClass 必须实现Serializable ObjectOutputStream 用于序列号对象
 */
public <T> void writeCacheFile(Context context, T mClass, String fileName) {

	ObjectOutputStream out = null;
	try {
		File file = new File(context.getCacheDir(), fileName);
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		FileOutputStream file_out = new FileOutputStream(file);
		out = new ObjectOutputStream(file_out);
		out.writeObject(mClass);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (out != null) {
			try {
				out.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}

}缓存

注意点:单例操做类中不要传入Actiivty的引用,以避免形成activity回收不了,最好传入applicationcontextapp

相关文章
相关标签/搜索