java实现多线程下载网络文件

package com.zkq.dowload;

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://192.168.1.186:8080/web/setup_8.8.0.2001b.exe";
		new MulThreadDownload().download(path,3);
	}
	/**
	 * 下载
	 * @param path	网络文件地址
	 * @param threadsize	线程数
	 * @throws Exception
	 */
	private 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();//获取网络文件的长度
			String filename=getFileName(path);
			//可以在这里设置文件的保存路径 如:"d:/data/"+filename
			File file=new File(filename);
			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("下载失败");
		}
	}
	/**
	 * 获取文件名称
	 * @param path
	 * @return
	 */
	private String getFileName(String path) {
		return path.substring(path.lastIndexOf("/")+1);
	}
	
	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){
					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();
			}
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值