文件缓存(配合JSON数组)
更新时间:2016年11月27日 17:17:26 作者:妖久
这篇文章主要介绍了文件缓存(配合JSON数组)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
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; }
以上所述是小编给大家介绍的文件缓存(配合JSON数组),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
相关文章
Android使用Sensor感应器实现线程中刷新UI创建android测力计的功能
这篇文章主要介绍了Android使用Sensor感应器实现线程中刷新UI创建android测力计的功能,实例分析了Android使用Sensor感应器实现UI刷新及创建测力器的技巧,需要的朋友可以参考下2015-12-12Android使用RecyclerView实现今日头条频道管理功能
这篇文章主要为大家详细介绍了Android使用RecyclerView实现今日头条频道管理功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-07-07
最新评论