2012-02-21 45 views
0

整個輸入流我試圖讀取服務器的響應,並將其從InputStream轉換爲字符串,但出現問題,我現在無法看到爲什麼。不讀取android

InputStream is = entity.getContent(); 
FileOutputStream folder = new FileOutputStream(
      Environment.getExternalStorageDirectory() 
        + "/test.xml"); 
try { 
byte[] buf = new byte[1048576]; 
int current = 0; 
int newCurrent = 0; 
while ((current = is.read(buf)) != -1) { 
    newCurrent = newCurrent + current; 
    folder.write(buf, 0, current); 
} 
System.out.println("returned folder" + folder); 
folder.flush(); 
} catch (IOException e) { 
     System.out.println("error on reading input: " + e.getMessage()); 
    } 

這是錯誤:

error on reading input: Socket closed 

這是我得到的錯誤,我不明白一個問題是,爲什麼它不讀取從InputStream中的全部內容(也許是因爲它的所有在一行?)。 謝謝。

回答

3

你不需要一次性讀取整個流,並把它放在一個字節數組,其實你的配件通過while循環讀取,並把內容在逐漸文件流:

int count; 
byte[] filebytes = new byte[1024]; 
while((count = is.read(filebytes)) != -1){ 
    folder.write(filebytes, 0, count); //writing buffer into file 
} 
in.close(); 
folder.flush(); 
folder.close(); 
+0

也試過這個....同樣的「套接字關閉」錯誤.. – 2012-02-21 15:33:31

+0

你沒有提到套​​接字在你的代碼中 – waqaslam 2012-02-21 15:58:13

+0

現在起作用了,這是我的錯。我減少了緩衝區大小到1024,它工作。我不明白套接字錯誤,爲什麼我收到它。謝謝 – 2012-02-25 23:45:26

0

根據當你的代碼使用的時候,stacktrace你的崩潰發生在readLine()read(buf)

這些匹配在一起嗎?