Best practices to read JSON from URL, and store it

2019-08-31 12:39发布

I am using GSON to parse some JSON feeds in various of my applications.

I used this tutorial and this code to make it work: http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);

//***************************************************
//Should I add some code here to save to SDCARD?
//***************************************************

SearchResponse response = gson.fromJson(reader, SearchResponse.class);
List<Result> results = response.results;
for (Result result : results) {
    Toast.makeText(this, result.fromUser, Toast.LENGTH_SHORT).show();
}

My question is set in the comment: What should I do to save this InputStreamReader to my SDCArd for an offline use?

I Googled a lot but cannot find a way to achieve this.

I guess that once I will have the answer, I will replace the 3 first line of code with:

InputStream source = new InputStream("/sdcard/my_json_file.txt");

Thank a lot for any help, I guess I am not the only one that need to achieve that...

1条回答
放我归山
2楼-- · 2019-08-31 13:03
  1. Create a FileOutputStream for the file you want to write to.
  2. Copy source to the FileOuputStream you created - see below -
  3. Close source
  4. Do like you said and create a new FileInputStream from path to the created file
  5. Send this new stream to your InputStreamReader

     public static void copyStream(InputStream input, OutputStream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.read(buffer, 0, buffer.length)) > 0)
            {
                output.write (buffer, 0, read);
            }
        }
    
查看更多
登录 后发表回答