1

次のコードを使用して、URL からファイルをダウンロードします。

while(status==Status.DOWNLOADING){
  HttpURLConnection conn=(HttpURLConnection)url.openConnection();
  conn.connect();
  int size=conn.getContentLength();
  BufferedInputStream bin=new BufferedInputStream(conn.getInputStream());
  byte[] buffer=new byte[1024];
  int read=bin.read(buffer);
  if(read==-1)
    break; 
  downloaded+=read;
}

一部の URL の read() メソッドでは、ダウンロードのサイズ (コンテンツの長さ) まで読み取る前に -1 を返します。

このコードで何が起こっているのか、誰でも私に提案できますか..

plsはあなたの提案を提供..

4

1 に答える 1

1

Web サーバーが http ヘッダーでコンテンツの長さを提供することは保証されていません。したがって、それに依存するべきではありません。次のようにストリームを読むだけです。

ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = bin.read(buf)) > 0) {
    bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();
于 2011-06-19T19:50:29.717 に答える