多线程断点续传下载文件

package com.multidownload.zz;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;

public class MultiDownLoad {
	
	public static int threadCount=8;
	
	public static Integer finishThread=threadCount;
	
	static String path="http://localhost:8080/MultiDownLoad/android-studio-bundle-145.3360264-windows.exe";
	
	static String detPth="D:/android-studio-bundle-145.3360264-windows.exe";

	public static void main(String[] args) throws Exception {
				
		URL url=new URL(path);
		
		URLConnection con = url.openConnection();
		con.connect();
		long contentLength = con.getContentLengthLong();
		
		long eachThreadDownLoadsize=contentLength/threadCount;
		
		for(int i=0;i<threadCount;i++){
			long start=i*eachThreadDownLoadsize;
			long end=(i+1)*eachThreadDownLoadsize-1;
			if(i==threadCount)end=contentLength-1;
			File file=new File("D:/"+i+".txt");
			if(!file.exists()){
				mutiDownLoad(i,start,end);
			}else{
				BufferedReader br=new BufferedReader(new FileReader(file));
				String startAndEnd = br.readLine();
				br.close();
				String[] result = startAndEnd.split("=");
				mutiDownLoad(i,Long.valueOf(result[0]),Long.valueOf(result[1]));
			}
			
		}
		
		
	}
	
	static void mutiDownLoad(final int threadId,final long start,final long end){
		
		new Thread(){
			public void run() {
				RandomAccessFile raf = null;
				
				
				try {
					URL url = new URL(path);
					URLConnection con = url.openConnection();
					con.setRequestProperty("Range","bytes="+start+"-"+end);
					con.setConnectTimeout(5000);
					con.setReadTimeout(5000);
					con.connect();
					InputStream responseIn = con.getInputStream();
					File file = new File(detPth);
					raf=new RandomAccessFile(file, "rwd");
					raf.seek(start);
					byte[] buffer=new byte[1024];
					int len=0;
					long total=0;
					File record=new File("D:/"+threadId+".txt");
					
					while((len=responseIn.read(buffer))!=-1){
						raf.write(buffer, 0, len);
						total+=len;
						FileWriter fw=new FileWriter(record,false);
						fw.write(start+total-1+"="+end);
						fw.close();
					}
					synchronized (MultiDownLoad.finishThread) {
						if(--MultiDownLoad.finishThread==0){
							for(int i=0;i<threadCount;i++){
								File deletef=new File("D:/"+i+".txt");
								deletef.delete();
							}
						}
					}
					System.out.println(threadId+"---------"+total);
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					try {
						raf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		 
	}
}

  

posted @ 2017-04-06 14:19  Nreo  阅读(121)  评论(0编辑  收藏  举报