將數據緩存到file中,便於下次恢復數據,或者預先加載。java
Cache管理類: ObjectOutputStream及Serializable 的api,,自行查看 java文檔android
public class CacheManager {api
public static CacheManager mInstance; static { mInstance = new CacheManager(); //單例 } private CacheManager() { } public <T> T readCacheFile(Context context, T t, String fileName) { ObjectInputStream in = null; try { File file = new File(context.getCacheDir(), fileName); if (!file.exists()) { return null; } //下步操做,也能夠用android 中context對象來獲取 流 FileInputStream file_in = new FileInputStream(file); in = new ObjectInputStream(file_in); t = (T) in.readObject(); return t; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (Exception e2) { e2.printStackTrace(); } } } } /* * mClass 必須實現Serializable ObjectOutputStream 用於序列號對象 */ public <T> void writeCacheFile(Context context, T mClass, String fileName) { ObjectOutputStream out = null; try { File file = new File(context.getCacheDir(), fileName); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream file_out = new FileOutputStream(file); out = new ObjectOutputStream(file_out); out.writeObject(mClass); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
}緩存
注意點:單例操做類中不要傳入Actiivty的引用,以避免形成activity回收不了,最好傳入applicationcontextapp