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...
- Create a FileOutputStream for the file you want to write to.
- Copy
source
to the FileOuputStream you created - see below - - Close
source
- Do like you said and create a new FileInputStream from path to the created file
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); } }
精彩评论