java 多线程下载文件

1.基本思路


2.源码

package cn.itcast.download;

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

public class MulThreadDownload {
public static void main(String[] args) throws Exception {
	String path = "http://localhost:8080/web/Dreamweaver.exe";
	new MulThreadDownload().download(path,3);
}
/**
 * ************************
 * *0*1*2*3*4*5*6*7*8*9*10* 文件字节
 * ************************
 * threadid:0 1 2
 * int block = 4 每一个下载多少
 * int start = threadid*block 开始位置
 * int end = (threadid+1)*block-1 结束位置
 */
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();
		//new File中的参数如果直接写名字,那么表示绝对路径,会存放在当前项目下;
		File file = new File(getFilename(path));
		//RandomAccessFile是用来访问那些保存数据记录的文件的,其大小和位置必须是可知的,它可以指定seek,搜索指定的位置,在指定位置写入数据;
		//rwd 参数是权限,表示将读取到的资源立马写入文件中;
		//多线程下载先要生成一个大小一样的文件,在进行写入;
		RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
		accessFile.setLength(length);
		accessFile.close();
		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.block=block;
		this.threadid=threadid;
		this.url=url;
		this.file=file;
	}
	@Override
		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()==200){
				InputStream inputStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len=inputStream.read(buffer))!=-1) {
					accessFile.write(buffer,0,len);
				}
				accessFile.close();
			}
			accessFile.close();
			System.out.println("第"+threadid+"线程已经下载完成");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		}
	
}
private String getFilename(String path) {
	
	return path.substring(path.lastIndexOf("/")+1);
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值