您的位置:首页 > 移动开发 > Android开发

android 将数据缓存在文件中,放在/data/data/<package name>/files目录下

2016-08-04 10:37 113 查看
我们的目的是把数据缓存到/data/data/<package name>/files目录下,

/**
* 保存对象
* @param ser
* @param file
* @throws IOException
*/
public static boolean saveObject(Context context, Serializable ser,
String file) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = context.openFileOutput(file, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ser);
oos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
oos.close();
	    fos.close();
} catch (Exception e) { } }}


/**
* 读取对象
* @param file
* @return
* @throws IOException
*/
public static Serializable readObject(Context context, String file) {
if (!isExistDataCache(context, file))
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = context.openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e) {
} catch (Exception e) {
e.printStackTrace();
// 反序列化失败 - 删除缓存文件
if (e instanceof InvalidClassException) {
File data = context.getFileStreamPath(file);
data.delete();
}
} finally {
try {
ois.close();
	    fis.close();
} catch (Exception e) { } } return null;}


/**
* 判断缓存是否存在
* @param cachefile
* @return
*/
public static boolean isExistDataCache(Context context, String cachefile) {
if (context == null)
return false;
boolean exist = false;
File data = context.getFileStreamPath(cachefile);
if (data.exists())
exist = true;
return exist;
}


记得要缓存的数据要实现Serializable接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: