我们的目的是把数据缓存到/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接口。