运用java.net.HttpURLConnection实现java多线程下载文件

直接上代码!!!
package com.qingda;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.plaf.synth.SynthStyle;
public class Main {
 // private final int a;
 private String path;
 private String localFile;
 private int threadNum;
 private int size;
 private MyThread[] thread;
 private ExecutorService executor;
 public Main(String path, String localFile, int threadNum) {
  this.path = path;
  this.localFile = localFile;
  this.threadNum = threadNum;
  thread = new MyThread[threadNum];
  executor = Executors.newCachedThreadPool();
 }
 public void downLoad() throws IOException {
  // int a;
  URL url = new URL(path);
  HttpURLConnection http = (HttpURLConnection) url.openConnection();
  http.setConnectTimeout(5 * 1000);
  http.setRequestMethod("GET");
  http.setRequestProperty("Accept", "text/txt,image/jpg");
  http.setRequestProperty("Accept-Language", "zh-CN");
  http.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
  http.setRequestProperty("Connection", "Keep-Alive");
  size = http.getContentLength();
  http.disconnect();
  // RandomAccessFile raf=new RandomAccessFile(localFile, "rws");
  int threadSize = size / threadNum + 1;
  for (int i = 0; i < threadNum; ++i) {
   int start = i * threadSize;
   RandomAccessFile raf = new RandomAccessFile(localFile, "rw");
   raf.seek(start);
   new Thread(new MyThread(start, threadSize, raf));
   thread[i] = new MyThread(start, threadSize, raf);
   executor.execute(new Thread(thread[i]));
   // new Thread(thread[i]).start();
  }
 }
 public double getCompleteRate() {
  int i = 0;
  int sumSize = 0;
  for (i = 0; i < threadNum; ++i) {
   sumSize += thread[i].hasRead;
  }
  return sumSize * 1.0 / size;
 }
 public static void main(String[] args) {
  long t1 = System.currentTimeMillis();
  Main m = new Main("http://www.baidu.com/img/bd_logo1.png", "D:/test.png", 4);// 百度主页logo
  try {
   m.downLoad();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  new Thread(new Runnable() {
   @Override
   public void run() {
    while (m.getCompleteRate() < 1) {
     System.out.printf("%s:%.2f\n", "已完成", m.getCompleteRate());
     try {
      Thread.sleep(10);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    long t2 = System.currentTimeMillis();
    System.out.println(t2 - t1);
    m.executor.shutdown();// 关闭
   }
  }).start();
 }
 private class MyThread implements Runnable {
  private int start;
  private int threadSize;
  private RandomAccessFile raf;
  public int hasRead;
  public MyThread(int start, int threadSize, RandomAccessFile raf) {
   this.start = start;
   this.threadSize = threadSize;
   this.raf = raf;
  }
  @Override
  public void run() {
   try {
    URL url = new URL(path);
    HttpURLConnection http = (HttpURLConnection) url.openConnection();
    http.setConnectTimeout(5 * 1000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Accept", "text/txt,image/jpg");
    http.setRequestProperty("Accept-Language", "zh-CN");
    http.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
    http.setRequestProperty("Connection", "Keep-Alive");
    http.setRequestProperty("Range", "bytes=" + start + "-" + start + threadSize);// 设置传输该线程下载文件部分
    // InputStream in=http.getInputStream();
    // System.out.println(http.getLastModified());
    // System.out.println(http.getContentType());
    // in.skip(start);
    BufferedInputStream in = new BufferedInputStream(http.getInputStream());//运用缓冲流
    byte[] b = new byte[1024];
    int num = 0;
    while (hasRead < threadSize && ((num = in.read(b)) != -1)) {
     hasRead += num;
     // num=0;
     raf.write(b, 0, num);
    }
    raf.close();
    in.close();
   } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值