檔案快取(配合JSON陣列)

發表於2016-12-13
1.   寫入快取:建立資料夾,把list集合裡面的陣列轉換為JSON陣列,存入資料夾
2.  讀取快取:把JSON陣列從資料夾裡面讀取出來,然後放入list集合,返回list集合

private final static File filefolder=new File("/sdcard/myData");
private final static File filename=new File("/sdcard/myData/tem.txt"); public static boolean writeCache(List<Data> list) { if(!filefolder.exists()) filefolder.mkdirs(); try { JSONArray array=new JSONArray(); for(int i=0;i<list.size();i++) { Data data=list.get(i); JSONObject ob=new JSONObject(); ob.put("name", data.getName()); ob.put("reason", data.getReason()); array.put(ob); } FileWriter fw=new FileWriter(filename); fw.write(array.toString()); fw.close(); } catch(Exception e) { e.printStackTrace(); return false; } return true; } public static List<Data> readCache() throws JSONException,IOException { if(!filefolder.exists()) filefolder.mkdir(); List<Data> list=new ArrayList<Data>(); if(filename.exists()) { FileInputStream in=new FileInputStream(filename); String line=null; StringBuffer sb=new StringBuffer(""); BufferedReader br=new BufferedReader(new InputStreamReader(in)); while((line=br.readLine())!=null) sb.append(line); br.close(); in.close(); JSONArray array=new JSONArray(sb.toString()); for(int i=0;i<array.length();i++) { JSONObject ob=new JSONObject(); ob=array.getJSONObject(i); Data data=new Data(); data.setName(ob.getString("name")); data.setReason(ob.getString("reason")); list.add(data); } } return list; }
複製程式碼

相關文章