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。我应该使用 Channels 来提高性能吗?

请通过观看我的代码来指导我以提高下载速度。

4

1 回答 1

0

InputStream用 a包装BufferedInputStream并增加缓冲区大小。切换到通道实现在客户端不会有太大改进,即使它在服务器端使用起来相当不错。

您还应该只创建一个byte[]并重用它。不要在循环中的每次迭代中创建它。

于 2011-06-07T14:59:28.290 回答