开发者

Best practices to read JSON from URL, and store it on SDCard for offline use

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 he开发者_开发问答re 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. 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);
            }
        }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜