2013-03-13 61 views
1

我正在開發一個Android應用程序,它將在流中獲取大塊JSON數據。調用Web服務是好的,但我有一點問題。在我以前的版本中,我使用Gson讀取數據流,然後嘗試將數據插入數據庫,除了性能以外,沒有任何問題。所以我試圖改變加載數據的方法,我試圖先讀取char[]的數據,然後將它們插入數據庫。從HttpGet的web服務讀取char [] - 奇怪的行爲

這是我的新代碼:

HttpEntity responseEntity = response.getEntity(); 
final int contentLength = (int) responseEntity.getContentLength(); 
InputStream stream = responseEntity.getContent(); 
InputStreamReader reader = new InputStreamReader(stream); 

int readCount = 10 * 1024; 
int hasread = 0; 
char[] buffer = new char[contentLength]; 
int mustWrite = 0; 
int hasread2 = 0; 
while (hasread < contentLength) { 
    // problem is here 
    hasread += reader.read(buffer, hasread, contentLength - hasread); 
} 

Reader reader2 = new CharArrayReader(buffer); 

的問題是,讀者正確啓動,但在讀取流結束的臨近,hasread變量值下降(由1)而不是增加。我很奇怪,然後while循環永遠不會結束。這段代碼有什麼問題?

+0

看了你的文章。請給我點你的解決方法。 – 2016-01-05 15:18:09

回答

2

您應該爲緩衝區使用固定大小,而不是整個數據的大小(contentLength)。注意:char[]陣列的長度與byte[]陣列的長度不同。數據類型是一個單一的16位Unicode字符。而byte數據類型是一個8位有符號二進制補碼整數。

而且你while循環是錯誤的,你可以修復它爲:

import java.io.BufferedInputStream; 

private static final int BUF_SIZE = 10 * 1024; 

// ... 

HttpEntity responseEntity = response.getEntity(); 
final int contentLength = (int) responseEntity.getContentLength(); 
InputStream stream = responseEntity.getContent(); 
BufferedInputStream reader = new BufferedInputStream(stream); 

int hasread = 0; 
byte[] buffer = new byte[BUF_SIZE]; 
while ((hasread = reader.read(buffer, 0, BUF_SIZE)) > 0) { 
    // For example, convert the buffer to a String 
    String data = new String(buffer, 0, hasread, "UTF-8"); 
} 

確保使用自己的字符集("UTF-8""UTF-16" ...)。

+0

它通過Gson(流模型)得到閱讀好,但我不會使用Gson。 – Areff 2013-03-13 20:39:20

+0

執行時出錯 Areff 2013-03-13 20:40:23

+0

@Lia Vung如果我使用InputStreamReader?,InputStreamReader和BufferedStreamReader的主要區別是什麼?第一個代碼(我的代碼)有什麼問題?因爲它沒有得到任何錯誤,只是錯誤的值在流的末尾被讀取爲可讀。 – Areff 2013-03-13 20:42:23