2011-10-14 12 views
0

我正在使用GSON在各种应用程序中解析某些JSON订阅源。从URL读取JSON并将其存储在SDCard中以供脱机使用的最佳做法

我使用本教程和这个代码,使其工作: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(); 
} 

我的问题是设置在注释: 我应该怎么做这个的InputStreamReader保存到SD卡我为脱机使用?

我GOOGLE了很多,但无法找到一种方法来实现这一点。

我想这一次我将有答案,我会取代的代码与3第一行:

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

感谢很多的帮助,我想我不是需要的唯一一个实现...

回答

0
  1. 为要写入的文件创建FileOutputStream。
  2. 复制source到您创建的FileOuputStream - 见下文 -
  3. 关闭source
  4. 难道像你说的,并创建路径中的新的FileInputStream所创建的文件
  5. 发送此新流您的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); 
         } 
        } 
    
相关问题