android 将数据缓存在文件中,放在/data/data/<package name>/files目录下
2016-08-04 10:37
113 查看
我们的目的是把数据缓存到/data/data/<package name>/files目录下,
记得要缓存的数据要实现Serializable接口。
/** * 保存对象 * @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接口。
相关文章推荐
- Android-->将布局文件放在服务器上,动态改变布局。
- Libs文件夹下的Jar文件为什么不会自动放在Android Private Libraries目录下
- android关于通过向导安装放在data分区下的apk文件
- android的数据与访问(1)-我的app配置参数文件放在哪儿?
- Libs文件夹下的Jar文件为什么不会自己主动放在Android Private Libraries文件夹下
- Android开发:文件放在哪个文件夹
- 怎么把Android放在C盘的默认文件及缓存移到指定的路径
- Android 把自己应用放在某种类型文件的打开列表,并获取文件的路径
- 在android中的文件放在不同位置也有不同的读取方式
- android: SQLiteOpenHelper,会将数据库放在当前应用程序的某个文件下(14)
- 奇怪的问题:js代码只能放在代码中不能引用文件
- .ASPX文件编译后是放在什么位置
- Spring的资源绑定的文件要放在类路径里
- Android源码构建工具速览(二)—— 清单文件
- 接口能否都放在单独的DLL文件中?
- Symbol MC1000 扫描 冲突问题 把下面文件做成scanwedge.reg的注册表文件,放在Application重起
- Android模拟J2ME的JSR75的文件管理开发
- 模板函数的声明和定义都放在.h文件
- 我的图象是JPEG文件,是放在远程一个固定IP电脑下面的一个目录,我如何读取这个JPEG文件呢?
- 高焕堂android中文书全,电子文件for version 1.0