使用缓存文件存取数据

来源:互联网 发布:照片查重软件 编辑:程序博客网 时间:2024/05/18 13:42
在客户端应用中,有时需要将本次下载的数据存储下来,等下次进入程序后加载已存储的数据,一般用于信息条目的显示,这样可以节省流量并保证较好的用户体验,等用户进行刷新时再从网络拉取新的数据,现在的新浪微博客户端就是这种思想。实现方法:
/** * 得到bean对象 *  * @return */public NewsList getNewsList() {NewsList newsList;String key = "cache_file";// 网络连接正常且不从缓存读取的时候进行数据下载if (isNetworkConnected() && !isReadDateCache(key)) {newsList = ApiClient.getNewsList(this, 1, 0, 20);// 下载的数据不为null则存入缓存文件if (newsList != null) {saveObject(key, newsList);}} else {// 缓存文件为空或网络不可用时读取缓存newsList = (NewsList) readObject(key);if (newsList == null) {newsList = new NewsList();}}return newsList;}/** *  * 判断是否从缓存读取 */public boolean isReadDateCache(String key) {return readObject(key) != null;}/** *  * 读取对象 */public Object readObject(String key) {if (!isDataCacheExist(key)) {return null;}FileInputStream fis = null;ObjectInputStream ois = null;try {fis = openFileInput(key);ois = new ObjectInputStream(fis);return (Serializable) ois.readObject();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();if (e instanceof InvalidClassException) {// 反序列化失败 - 删除缓存文件File file = getFileStreamPath(key);file.delete();}}return null;}/** *  * 判断缓存文件是否存在 */public boolean isDataCacheExist(String cacheFile) {boolean isExist = false;File file = getFileStreamPath(cacheFile);if (file.exists()) {isExist = true;}return isExist;}/** *  * 保存对象 */public boolean saveObject(String key, Serializable ser) {FileOutputStream fos = null;ObjectOutputStream oos = null;try {fos = openFileOutput(key, Context.MODE_PRIVATE);oos = new ObjectOutputStream(fos);oos.writeObject(ser);oos.flush();return true;} catch (Exception e) {// TODO: handle exceptionreturn false;} finally {try {oos.close();fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

主要用到了对象流对实现了可序列化接口的对象进行传输。openFileOutput()和openFileInput()方法是SDK的方法,用以在程序的file文件夹下得到文件。

判断联网状态的方法比较简单,前面的博文也有介绍,这里不再介绍。

原创粉丝点击