2016-02-17 56 views
0

如何下載和使用改造,甚至獲得更好的接收改造讀取文本文件?Android的改造下載/閱讀文本文件從服務器

下面是一個示例是如何改造的時間之前完成。 真的會是怎樣的代碼 樣品轉換低於改造:

try { 
    // Create a URL for the desired page 
    URL url = new URL("ksite.com/thefile.txt"); 

    // Read all the text returned by the server 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
    String str; 
    while ((str = in.readLine()) != null) { 
     // str is one line of text; readLine() strips the newline character(s) 
    } 
    in.close(); 
} catch (MalformedURLException e) { 
} catch (IOException e) { 
} 

我真的很感謝你的幫助。由於

回答

1

編輯: 有因爲版本@Streaming註釋改造1.6,可用於輸送原料InputStream。可用於下載文件。

IMO改造是不是下載文件(除非該文件包含JSON)的最佳工具。

使用改造(版本2)意味着使用的是OkHttp引擎蓋下。 OkHttp是下載文件的更好工具。

與OkHttp異步得到如下:

recipes section on Github
private final OkHttpClient client = new OkHttpClient(); 

    public void run() throws Exception { 
    Request request = new Request.Builder() 
     .url("http://publicobject.com/helloworld.txt") 
     .build(); 

    client.newCall(request).enqueue(new Callback() { 
     @Override public void onFailure(Request request, IOException throwable) { 
     throwable.printStackTrace(); 
     } 

     @Override public void onResponse(Response response) throws IOException { 
     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 

     Headers responseHeaders = response.headers(); 
     for (int i = 0; i < responseHeaders.size(); i++) { 
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); 
     } 

     System.out.println(response.body().string()); 
     } 
    }); 
    } 

更多。

同樣來自維基:

上響應身體的串()方法是方便和有效的用於 小的文件。但是,如果響應正文很大(大於1 MiB),請避免使用string(),因爲它會將整個文檔加載到 內存中。在這種情況下,更願意將流體作爲流處理。

編輯: 使用RxJava

public interface Api { 

    @Streaming 
    @GET("path to file") 
    Observable<ResponseBody> getFile(); 
} 

api.getFile() 
      .flatMap(responseBody -> { 
       try { 
        return Observable.just(responseBody.string()); 
       } catch (IOException e) { 
        return Observable.error(e); 
       } 
      }) 
      .subscribeOn(Schedulers.io()) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(System.out::println); 

同樣,你可能不應該使用responseBody.string()更大的文件。

+0

謝謝,我需要處理的身體流。試試吧 – Joolah

+1

任何機會都可以用AndroidRx改進這段代碼?謝謝 – Joolah