Java多線程下載檔案

來源:互聯網
上載者:User

標籤:

package com.test.download;  import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL;  /*   * 多線程下載   */ public class MulThreadDownload {       public static void main(String[] args) throws Exception {          String path = "http://pic.4j4j.cn/upload/pic/20130909/681ebf9d64.jpg" ;          new MulThreadDownload().download(path, 3 );      }            public void download (String path, int threadsize) throws Exception{          URL url = new URL(path);          HttpURLConnection conn = (HttpURLConnection) url.openConnection();          conn.setConnectTimeout( 5000 );          conn.setRequestMethod( "GET" );          if (conn.getResponseCode() == 200 ){              //擷取網路檔案長度              int length = conn.getContentLength();                //建立本地檔案儲存下載資料              File file = new File(getFilename(path));              //計算每條線程負責下載的資料量              int block = length%threadsize== 0 ? length/threadsize : length/threadsize+ 1 ;              //開啟指定數目的線程同時下載              for ( int threadid = 0 ; threadid < threadsize; threadid++){                  new DownloadThread(threadid,block,url,file).start();              }          } else {              System.out.println( "下載失敗!" );          }      }            private class DownloadThread extends Thread{          private int threadid;   //線程編號          private int block;      //下載塊大小          private URL url;        //下載連結          private File file;      //下載資料儲存檔案          public DownloadThread( int threadid, int block, URL url, File file) {              this .threadid = threadid;              this .block = block;              this .url = url;              this .file = file;          }           public void run() {              int start = threadid * block;       //本線程下載資料寫入檔案開始位置              int end = (threadid+ 1 ) * block - 1 ; //本線程下載資料寫入檔案結束位置              try {                  //建立一個隨機訪問檔案流對象                  RandomAccessFile accessFile = new RandomAccessFile(file, "rwd" );                  //檔案指標位移至正確寫入位置                  accessFile.seek(start);                  HttpURLConnection conn = (HttpURLConnection) url.openConnection();                  conn.setConnectTimeout( 5000 );                  conn.setRequestMethod( "GET" );                  //佈建要求資料的範圍                  conn.setRequestProperty( "Range" , "bytes=" +start+ "-" +end);                  if (conn.getResponseCode() == 206 ){ //狀態代碼206:(部分內容) 伺服器成功處理了部分 GET 請求                      InputStream inStream = conn.getInputStream();                      byte [] buffer = new byte [ 1024 ];                      int len = 0 ;                      while ((len = inStream.read(buffer)) != - 1 ){                          accessFile.write(buffer, 0 , len);                      }                      accessFile.close();                      inStream.close();                  }                  System.out.println( "第" +(threadid+ 1 )+ "部分下載完成" );              } catch (Exception e) {                  e.printStackTrace();              }          }      }       private String getFilename(String path) {          return path.substring(path.lastIndexOf( "/" )+ 1 );      } }

Java多線程下載檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.