JAVA 多线程下载文件

package MutilDownLoad;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
	protected static String path = "http://localhost:8080/app/dd.jpg";// 网址,这里采用本机的服务器
	protected static int threadcount = 3;// 开的线程数量

	public static void main(String args[]) {
		//发送get请求,请求这个地址的资源
		try {
			URL url = new URL(path);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 得到URL链接

			conn.setRequestMethod("GET");// 设置GET请求
			conn.setConnectTimeout(5000);// 设置请求时间
			conn.setReadTimeout(5000);// 设置响应时间

			if (conn.getResponseCode() == 200) {
				int length = conn.getContentLength();
				//设置文件的大小
				File file = new File(getFileName(path));
				 //生成临时文件
				RandomAccessFile raf = new RandomAccessFile(file, "rwd");
				raf.setLength(length);
				//计算每个线程应该下载多少个字节
				int size = length / threadcount;
				for (int i = 0; i < threadcount; i++) {
					//计算线程下载的开始位置和结束位置
					int startIndex = i * size;
					int endIndex = (i + 1) * size - 1;
					//如果是最后一个线程,那么位置写死
					if (i == threadcount - 1) {
						endIndex = length - 1;
					}
					MyThread t=new MyThread(startIndex, endIndex, i, path);
					Thread thread=new Thread(t);
					thread.start();
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getFileName(String path) {
		int index = path.lastIndexOf("/");
		return path.substring(index + 1);
	}
}

class MyThread implements Runnable {
	int startIndex;
	int endIndex;
	int threadId;
	String path;

	public MyThread(int startIndex, int endIndex, int threadId, String path) {
		super();
		this.startIndex = startIndex;
		this.endIndex = endIndex;
		this.threadId = threadId;
		this.path = path;
	}

	@Override
	public void run() {
		try {
			URL url = new URL(path);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 得到URL链接

			conn.setRequestMethod("GET");// 设置GET请求
			conn.setConnectTimeout(5000);// 设置请求时间
			conn.setReadTimeout(5000);// 设置响应时间
			//设置本次Http所请求的数据的区间
			conn.setRequestProperty("Range","bytes="+startIndex+"-"+endIndex );
			//请求部分数据,相应码是206
			if(conn.getResponseCode()==206)
			{
				//流里此时只有1/3的源文件
				InputStream is=conn.getInputStream();
				//拿到临时文件的输出流
				File file=new File("F:/dd.jpg");
				RandomAccessFile raf=new RandomAccessFile(file, "rwd");
				//把文件的写入位置移动到start
				raf.seek(startIndex);
				byte []b=new byte[1024];
				int len=0;
				while((len=is.read(b))!=-1)
				{
					raf.write(b, 0, len);
				}
				raf.close();
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值