1

次のコードを使用してダウンロードします...

public void run()
{
    RandomAccessFile file=null;    //download wiil be stored in this file
    InputStream in=null;           //InputStream to read from
    try
    {

         HttpURLConnection conn=(HttpURLConnection)url.openConnection();    
     conn.setRequestProperty("Range","bytes="+downloaded+"-");
     if(user!=null && pwd!=null){
        String userPass=user+":"+pwd;
        String encoding = new sun.misc.BASE64Encoder().encode (userPass.getBytes());
        conn.setRequestProperty ("Authorization", "Basic " + encoding); 
     }

         conn.connect();

     //..More code 

     if(status==Status.CONNECTING)
        status=Status.DOWNLOADING;


         file=new RandomAccessFile(location,"rw");
         file.seek(downloaded);
         in=conn.getInputStream();      
     byte[] buffer;     
         while(status==Status.DOWNLOADING)
         {
            if(size-downloaded>Constants.MAX_BUFFER_SIZE)  //MAX_BUFFER_SIZE=1024
      buffer=new byte[Constants.MAX_BUFFER_SIZE];
    else
      buffer=new byte[size-downloaded];

        int read=in.read(buffer);  //reading in Buffer

        if(read==-1)
           break;

       //write to file
        file.write(buffer,0,read);
        downloaded+=read;

        //..More code
        }  //end of while


}

上記のコードを使用して、URLからループでファイルをダウンロードしています。ダウンロード(読み取り)からInputStreamを使用しています。パフォーマンスを向上させるためにチャネルを使用する必要がありますか?

ダウンロード速度を上げるために私のコードを見て案内してください。

4

1 に答える 1

0

をでラップしInputStreamBufferedInputStreamバッファサイズを増やします。チャネル実装に切り替えても、サーバー側で使用するのがかなり良い場合でも、クライアント側ではあまり改善されません。

また、1つだけ作成byte[]して再利用する必要があります。ループ内の反復ごとに作成しないでください。

于 2011-06-07T14:59:28.290 に答える