2012-02-21 19 views
0

サーバからの応答を読み込み、それをInputStreamからStringに変換しようとしていますが、何かがうまくいかず、なぜ今私が見ることができません。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からコンテンツ全体を読み取らない理由を私は理解していない別の問題があります1行で?)。おかげさまで

答えて

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

これも試してみました。同じ "ソケットクローズ"エラーです。 –

+0

あなたのコードにソケットがありません。 – waqaslam

+0

これは私のせいでした。私はバッファサイズを1024に減らし、うまくいった。私はソケットエラーを理解していなかったし、なぜ私はそれを受け取った。どうも –

0

によると、あなたのコードの使用中にreadLine()でクラッシュが発生するstacktrace。 read(buf)

これらは一致しますか?

関連する問題