用java實現簡單的多線程下載

來源:互聯網
上載者:User

今天用java寫了一個簡單的HTTP多線程下載程式,主要用了HTTP協議和RandomAccessFile類來實現。很容易再加上斷點續傳功能,這樣就可以實作類別似“小小網路螞蟻”的功能了。

public class DownloadNetTest {
   private File fileOut;
   private URL url;
   private long fileLength=0;
   //初始化線程數
   private int ThreadNum=5;

   public DownloadNetTest(){
   try{
      System.out.println("正在連結URL"); 
      url=new URL("http://211.64.201.201/uploadfile/nyz.mp3");
      HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
      fileLength=urlcon.getContentLength();
      if(urlcon.getResponseCode()>=400){
      System.out.println("伺服器響應錯誤");
      System.exit(-1);
      }
      if(fileLength<=0)
      System.out.println("無法獲知檔案大小");
      //列印資訊
      printMIME(urlcon);
      System.out.println("檔案大小為"+fileLength/1024+"K");
      //擷取檔案名稱
      String trueurl=urlcon.getURL().toString();
      String filename=trueurl.substring(trueurl.lastIndexOf('/')+1);
      fileOut=new File("D://",filename);
   }
   catch(MalformedURLException e){
      System.err.println(e);
   }
   catch(IOException e){
      System.err.println(e);
   }
   init();
}
   private void init(){
      DownloadNetThread [] down=new DownloadNetThread[ThreadNum];
   try {
      for(int i=0;i<ThreadNum;i++){
         RandomAccessFile randOut=new RandomAccessFile(fileOut,"rw");
         randOut.setLength(fileLength);
         long block=fileLength/ThreadNum+1;
         randOut.seek(block*i);
         down[i]=new DownloadNetThread(url,randOut,block,i+1); 
         down[i].setPriority(7);
         down[i].start();
      }
   //迴圈判斷是否下載完畢
   boolean flag=true;
   while (flag) {
      Thread.sleep(500);
      flag = false;
      for (int i = 0; i < ThreadNum; i++)
      if (!down[i].isFinished()) {
      flag = true;
      break;
      }
  }// end while
   System.out.println("檔案下載完畢,儲存在"+fileOut.getPath() );
   } catch (FileNotFoundException e) {
         System.err.println(e);
         e.printStackTrace();
   }
   catch(IOException e){
      System.err.println(e);
      e.printStackTrace();
   }
   catch (InterruptedException e) {
   System.err.println(e);
   }

}
private void printMIME(HttpURLConnection http){
   for(int i=0;;i++){
   String mine=http.getHeaderField(i);
   if(mine==null)
   return;
   System.out.println(http.getHeaderFieldKey(i)+":"+mine);
   }
}

public static void main(String[] args) {
       DownloadNetTest app=new DownloadNetTest();
}

}


//線程類
public class DownloadNetThread extends Thread{
private InputStream randIn;
private RandomAccessFile randOut;
private URL url;
private long block;
private int threadId=-1;
private boolean done=false;

   public DownloadNetThread(URL url,RandomAccessFile out,long block,int threadId){
   this.url=url;
   this.randOut=out;
   this.block=block;
   this.threadId=threadId;
}
 public void run(){
   try{
      HttpURLConnection http=(HttpURLConnection)url.openConnection();
      http.setRequestProperty("Range","bytes="+block*(threadId-1)+"-");
      randIn=http.getInputStream();
   }
   catch(IOException e){
      System.err.println(e);
   }

   ////////////////////////
   byte [] buffer=new byte[1024];
   int offset=0;
   long localSize=0;
   System.out.println("線程"+threadId+"開始下載");
   try {
      while ((offset = randIn.read(buffer)) != -1&&localSize<=block) {
      randOut.write(buffer,0,offset);
      localSize+=offset;
      }
      randOut.close();
      randIn.close();
      done=true;
      System.out.println("線程"+threadId+"完成下載");
      this.interrupt();
   }
   catch(Exception e){
      System.err.println(e);
   }
}
  public boolean isFinished(){
     return done;
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.