黑马程序员--Java多线程断点续传下载

------- android培训java培训、期待与您交流! ----------
把这几天学的多线程、IO流、网络编程汇总,根据毕老师视频里的提示,写了一个支持断点续传的多线程下载
用到的知识点:
多线程的创建:继承Thread或者用Runnable接口
IO流中RandomAccessFile类相关方法的使用:seek(),readInt()、write()、writeInt()
File类中相关方法的使用:File()、exists()、delete()
字节输入流InputStream的读取方法:read()
HttpURLConnection类的使用:setConnectTimeout()、getContentLength()、setRequestProperty()
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MutThreadDown extends Thread{
	private static final String DIR_PATH = "E://Download";//下载目录
	private static final int THREAD_COUNT = 3;//下载线程数量
	private URL  url;//目标下载地址
	private File dataFile;//下载的存储文件
	private File tempFile;//用来存储每个线程下载的进度的临时文件
	private int  totalLength;//待下载文件的总长度
	private int  threadLength;//每个线程要下载的长度
	private int  finishLength;//当前已完成的长度
	private long beginTime;//开始下载时间
	public MutThreadDown(String address) throws IOException{
		url = new URL(address);//下载地址
		dataFile = new File(DIR_PATH,address.substring(address.lastIndexOf("/")+1));//创建本地文件
		tempFile = new File(dataFile.getAbsolutePath()+".temp");//创建临时文件
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(3000);  
			
			totalLength = conn.getContentLength();// 获取服务端发送过来的文件长度
			threadLength = (totalLength + THREAD_COUNT -1)/THREAD_COUNT;// 获取服务端发送过来的文件长度
			finishLength = 0;
			
			if(!tempFile.exists()){// 如果临时文件不存在 
				RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
				for (int i = 0; i < THREAD_COUNT; i++) {// 创建临时文件, 用来记录每个线程已下载多少
					raf.writeInt(0);
				}
				raf.close();
			}
			for (int i = 0; i < THREAD_COUNT; i++) {
				new DownLoadThread(i).start();  // 开启线程, 每个线程将会下载一部分数据到本地文件中
			}
			beginTime = System.currentTimeMillis();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	private class DownLoadThread extends Thread{
		private int ID;

		public DownLoadThread(int iD) {
			this.ID = iD;
		}
		@Override
		public void run() {
			try {
				RandomAccessFile tempRaf = new RandomAccessFile(tempFile, "rw"); // 记录进度的临时文件  
				tempRaf.seek(ID*4); // 将指针移动到当前线程的位置(每个线程写1个int值, 占4字节)  
				int threadFinish =tempRaf.readInt();  // 读取当前线程已完成了多少
				synchronized (this) {
					finishLength += threadFinish;// 统计所有线程总共完成了多少 
				}
				// 计算当前线程起始位置和结束位置
				int start = ID*threadLength + threadFinish;
				int end = ID*threadLength + threadLength-1;
				
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(3000);
				conn.setRequestProperty("Range", "bytes="+start+"-"+end); // 设置当前线程下载的范围 
				
				System.out.println("线程" + ID + "开始下载"+start+"-"+end); 
				
				InputStream in = conn.getInputStream();//获取连接的输入流
				RandomAccessFile dataRaf = new RandomAccessFile(dataFile, "rw");//保存数据的本地文件
				dataRaf.seek(start);//设置当前线程保存数据的位置
				//开始读取和写入数据
				byte[] buf = new byte[1024*100];
				int len = 0;
				while((len = in.read(buf))!=-1){
					dataRaf.write(buf, 0, len);//写入本地文件
					threadFinish += len;//统计当前线程完成量
					tempRaf.seek(ID*4);
					tempRaf.writeInt(threadFinish);//将当前线程完成了多少写入到临时文件
					synchronized (this) {
						finishLength += len;  // 统计所有线程总共完成了多少  
					}
				}
				in.close();
				tempRaf.close();
				dataRaf.close();
				System.out.println("线程" + ID + "下载完毕"); 
				if(totalLength == finishLength){// 如果已完成长度等于服务端文件长度(代表下载完成) 
					System.out.println("下载完成, 耗时: " + (System.currentTimeMillis() - beginTime));  
                    tempFile.delete();   
				}
				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		new MutThreadDown("需要下载文件的URL").start();
	}
}
其实迅雷等下载软件下载原理也是这样的,每一个服务器对下载的请求都有带宽限制的,所以多个线程下载从整体上是增加了下载的带宽,不过启动的线程也不是没有限制的,这个受限于你的真实的物理带宽。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值