File caching (with JSON array) _android

Source: Internet
Author: User
Tags stringbuffer

1. Write cache: Create a folder, convert the array in the list to a JSON array, and store it in a folder

2. Read cache: The JSON array is read from the folder, and then put into the list collection, return to the list collection

 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 ()) fil
    Efolder.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; }

The above is a small series to introduce the file cache (with JSON array), I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.