Android 离线缓存之文件缓存
数据缓存到本地,节省用户流量,减少出现加载中或加载失败提示.
缓存数据有很多种方法:
数据库缓存
- 数据库缓存
- 文件缓存
- sharedPreference缓存
各有优缺点,其中文件缓存比较方便快捷.
Activity有
context.openFileOutput(file, Context.MODE_PRIVATE)
和context.openFileInput(file)
,这两个方法提供了对文件写入和读取的原生支持,减少很多IO流的重复代码.
加上new ObjectOutputStream(fileOutputStream)
和new ObjectInputStream(fileInputStream)
这两个类对对象的序列化提供的支持.
从文件到对象变的非常方便和快捷
以下是代码:
对象的写入:
public void saveCashe(Serializable serializable, String file) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(serializable);
objectOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象的读取:
public Serializable getCashe(String file) {
if (!isExitCashe(file)){
return null;
}
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = openFileInput(file);
objectInputStream = new ObjectInputStream(fileInputStream);
Object o = objectInputStream.readObject();
return (Serializable) o;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
if (e instanceof ClassNotFoundException) {
File fileStreamPath = getFileStreamPath(file);
fileStreamPath.delete();
}
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectInputStream != null) {
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
文件存在与否的判断:
public boolean isExitCashe(String file){
File fileStreamPath = getFileStreamPath(file);
return fileStreamPath.exists();
}
注意
对象需要实现Serializable接口.Map,List默认都实现了Serializable,所以可以直接读取.
getFileOutput()
和getFileInput()
由context提供的支持,其文件存储在Data/Data/包名/file目录下面,只需要传入文件名即可.
以上为所有内容.
文章作者pompip,主要记录和分享coding中经验