6

私は現在、Web上にあるファイルを読み取り、電話のファイルに書き込む次のコードを持っています:

InputStream inputStream = new URL(sourceFileWebAddress).openStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);

int count;
byte buffer[] = new byte[1024];

while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1)
  fileOutputStream.write(buffer, 0, count);

ダウンロードを開始する前に読み取られる合計バイト数を決定することが可能かどうか (上記の設定を使用するか、別の方法で) (ダウンロードの進行中にパーセンテージの進行状況をユーザーに公開するため) を知っている人はいますか?

4

5 に答える 5

3

ダウンロードを開始するに読み取られる合計バイト数を決定するには、次のようにHTTPHEAD要求を送信することによってのみ応答ヘッダーを取得する方法があります。

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class SimpleHTTPRequest {

  public static void main(String[] args) {
      HttpURLConnection connection = null;
      URL serverAddress = null;

      try {
          String sourceFileWebAddress = "http://localhost:8080/mycontents";
          serverAddress = new URL(sourceFileWebAddress);
          //set up out communications stuff
          connection = null;

          //Set up the initial connection
          connection = (HttpURLConnection)serverAddress.openConnection();

          //HEAD request will make sure that the contents are not downloaded.
          connection.setRequestMethod("HEAD");  

          connection.connect();
          System.out.println("========"+connection.getContentLength());

      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (ProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      finally
      {
          //close the connection, set all objects to null
          connection.disconnect();

          connection = null;
      }
  }
}

これにより、実際にコンテンツをダウンロードせずに、ダウンロードするコンテンツのサイズが印刷されます。

于 2012-06-06T13:33:59.313 に答える
1

の方法getContentLengthURLConnection、ダウンロードするファイルのサイズがわかります。これから、新しいデータが fileOutputStream によって処理されるたびに、ProgressBar を好きなように描画して更新することができます (onProgressUpdate で、AsyncTask 内でこれを行っていると仮定します)。

サーバーが getContentLength の値を提供しない場合 (ほとんどの場合 -1 ですが、少なくともゼロ以下かどうかを確認してください)、ProgressBar を不確定にします。

于 2012-06-06T13:22:38.743 に答える