多线程下载WEB资源

多线程下载使用到的是随机文件访问类

代码如下:

 

package com.huawei;

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



/**
 * @author zhangzhao E-mail: zz198808@sina.com
 * @version 创建时间:2012-4-15 下午03:00:04
 * 类说明
 */
public class MulThreadDown {

	public static void main(String[] args) throws IOException {
		String path="http://59.69.105.217:8080/web/QQ2011.exe";
		new MulThreadDown().downLoad(path,3);
	}
	
	public void downLoad(String path,int threadNum) throws IOException{
		URL url=new URL(path);
		HttpURLConnection con=(HttpURLConnection)url.openConnection();
		con.setReadTimeout(5000);
		if(con.getResponseCode()==200)
		{
			int length=con.getContentLength();
			int block=length%threadNum==0?length/threadNum:length/threadNum+1;
			File file=new File(getFileName(path));
			RandomAccessFile randomAccessFile=new RandomAccessFile(file, "rwd");
			randomAccessFile.setLength(length);
			randomAccessFile.close();
			for(int threadID=0;threadID<threadNum;threadID++){
				new DownLoadThread(threadID,block,url,file).start();
			}
		}
		
	}
	private final 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;
		}
		@Override
		public void run() {
			int startPos=threadID*block;
			int endPos=(threadID+1)*block-1;
			try {
				RandomAccessFile randomAccessFile=new RandomAccessFile(file, "rwd");
				randomAccessFile.seek(startPos);
				HttpURLConnection con =(HttpURLConnection)url.openConnection();
				con.setReadTimeout(5000);
				con.setRequestMethod("GET");
				con.setRequestProperty("Range", "bytes="+startPos+"-"+endPos);
				//if(con.getResponseCode()==206)//分段的时候请求码不是200,是206
				//{
				System.out.println(con.getResponseCode());
					InputStream inputStream=con.getInputStream();
					int len=0;
					byte[] buffer=new byte[4*1024];
					while((len=inputStream.read(buffer))!=-1)
					{
						randomAccessFile.write(buffer, 0, len);
					}
					inputStream.close();
					randomAccessFile.close();
					System.out.println("第"+(threadID+1)+"条线程下载完成");
				//}
				
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
	}
	public String getFileName(String path)
	{
		int pos=path.lastIndexOf("/");
		return path.substring(pos+1);
		
	}
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值