`
猫不吃的鱼
  • 浏览: 157487 次
  • 性别: Icon_minigender_1
  • 来自: 芜湖市
社区版块
存档分类
最新评论

java多线程断点续传

    博客分类:
  • JAVA
 
阅读更多
请求头中包含如下 RANGE:bytes=2345-
意思是从2345字节处开始请求数据。这样如果在xx处下载失败,可以通过传递如上请求参数达到续传的目的。

DownloadApp
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Act:
 * User:于勇
 * Date: 12-12-24
 * version:1.0
 * To change this template use File | Settings | File Templates.
 */
public class DownloadTask extends Thread{
    private DownloadInfo info;
    private long start;
    private long length;

    public DownloadTask(DownloadInfo info){
        this.info=info;
    }

    public DownloadTask(DownloadInfo info,long start,long length){
        this.info=info;
        this.start=start;
        this.length=length;
        System.out.println("线程 "+this.getId()+" 开启");
    }
    
    @Override
    public void run() {
    	long tmpLen=0;
    	InputStream input=null;
    	RandomAccessFile tmpSaveFile=null;
        try{
            URL url=new URL(info.getdSourcePath());
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            String sProperty="bytes="+start+"-";
            httpURLConnection.setRequestProperty("User-Agent","NetFox");
            httpURLConnection.setRequestProperty("RANGE", sProperty);
            input =  httpURLConnection.getInputStream();
            byte[]b=new byte[DownloadInfo.THREAD_READ_LENGTH];
            int nRead;
            File tmpFile=new File(info.getdSavePath()+File.separator+info.getdSaveName()+".tmp");
            tmpSaveFile = new RandomAccessFile(tmpFile,"rw");
            if(tmpFile.exists()){
                    tmpSaveFile.seek(start);
            }
            while((nRead=input.read(b,0,DownloadInfo.THREAD_READ_LENGTH))>0&&tmpLen<length){
                tmpLen+=nRead;
                tmpSaveFile.write(b,0,nRead);
            }
            System.out.println("线程 "+this.getId()+" 下载完成!下载片段["+this.start+"字节至"+(this.start+length)+"字节]");
        }catch(Exception e){
            System.out.println("线程 "+this.getId()+" 出错");
            DownloadTask task=new DownloadTask(info,start+tmpLen,length-tmpLen);
            task.start();
            DownloadProject.totalThread++;
            System.out.println("线程 "+task.getId()+" 开启恢复 从 "+(start+tmpLen)+" ");
        }finally{
        	try {
				input.close();
				tmpSaveFile.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	DownloadProject.totalThread--;
        }


    }

    public long getLength() {
        return length;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public DownloadInfo getInfo() {
        return info;
    }

    public void setInfo(DownloadInfo info) {
        this.info = info;
    }

    public long getStart() {
        return start;
    }

    public void setStart(long start) {
        this.start = start;
    }

}



DownloadInfo
/**
 * Act:
 * User:于勇
 * Date: 12-12-24
 * version:1.0
 * To change this template use File | Settings | File Templates.
 */
public class DownloadInfo {
    private String dSourcePath;
    private String dSaveName;
    private String dSavePath;
    public static long THREAD_LENGTH=4096;//1024000
    public static int THREAD_READ_LENGTH=2048
    ;


    public DownloadInfo(String sourcePath,String savePath,String saveName){
        this.dSourcePath=sourcePath;
        this.dSaveName=saveName;
        this.dSavePath=savePath;
    }

    public String getdSourcePath() {
        return dSourcePath;
    }

    public void setdSourcePath(String dSourcePath) {
        this.dSourcePath = dSourcePath;
    }

    public String getdSaveName() {
        return dSaveName;
    }

    public void setdSaveName(String dSaveName) {
        this.dSaveName = dSaveName;
    }

    public String getdSavePath() {
        return dSavePath;
    }

    public void setdSavePath(String dSavePath) {
        this.dSavePath = dSavePath;
    }
}


DownloadProject
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Act:
 * User:于勇
 * Date: 12-12-24
 * version:1.0
 * To change this template use File | Settings | File Templates.
 */
public class DownloadProject extends Thread{
    public static int totalThread=0;
    private DownloadInfo info;

    public void setInfo(DownloadInfo info) {
        this.info = info;
    }

    @Override
    public void run() {
    	try{
        runThreads();
        while(totalThread>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		switchFile();
    	}
    }

    private void runThreads(){
        try{
            URL url=new URL(info.getdSourcePath());
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            String sProperty="bytes="+0+"-";
            httpURLConnection.setRequestProperty("RANGE", sProperty);
            InputStream input=  httpURLConnection.getInputStream();
            int length=httpURLConnection.getContentLength();
            File tmpFile=new File(info.getdSavePath()+File.separator+info.getdSaveName()+".tmp");
            long start=0;
            long compLen=0;
            if(tmpFile.exists()){
            	compLen=tmpFile.length();
                if(compLen<length){
                    start+=compLen;
                    length-=compLen;
                }else
                    return;
            }
            for(int i=1;i<=length/DownloadInfo.THREAD_LENGTH;i++){
                DownloadTask task=null;
                task=new DownloadTask(info,start,DownloadInfo.THREAD_LENGTH);
                task.start();
                totalThread++;
                start=start+DownloadInfo.THREAD_LENGTH;
            }

            if(length%DownloadInfo.THREAD_LENGTH!=0){
                DownloadTask task=new DownloadTask(info,start,length%DownloadInfo.THREAD_LENGTH);
                task.start();
                totalThread++;
                start+=length%DownloadInfo.THREAD_LENGTH;
            }
            input.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    private void switchFile(){
    	 File oldfile=new File(info.getdSavePath()+File.separator+info.getdSaveName()+".tmp");
    	 File newfile=new File(info.getdSavePath()+File.separator+info.getdSaveName());
    	 oldfile.renameTo(newfile);
    }
}


DownloadTask
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Act:
 * User:于勇
 * Date: 12-12-24
 * version:1.0
 * To change this template use File | Settings | File Templates.
 */
public class DownloadTask extends Thread{
    private DownloadInfo info;
    private long start;
    private long length;

    public DownloadTask(DownloadInfo info){
        this.info=info;
    }

    public DownloadTask(DownloadInfo info,long start,long length){
        this.info=info;
        this.start=start;
        this.length=length;
        System.out.println("线程 "+this.getId()+" 开启");
    }
    
    @Override
    public void run() {
    	long tmpLen=0;
    	InputStream input=null;
    	RandomAccessFile tmpSaveFile=null;
        try{
            URL url=new URL(info.getdSourcePath());
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            String sProperty="bytes="+start+"-";
            httpURLConnection.setRequestProperty("User-Agent","NetFox");
            httpURLConnection.setRequestProperty("RANGE", sProperty);
            input =  httpURLConnection.getInputStream();
            byte[]b=new byte[DownloadInfo.THREAD_READ_LENGTH];
            int nRead;
            File tmpFile=new File(info.getdSavePath()+File.separator+info.getdSaveName()+".tmp");
            tmpSaveFile = new RandomAccessFile(tmpFile,"rw");
            if(tmpFile.exists()){
                    tmpSaveFile.seek(start);
            }
            while((nRead=input.read(b,0,DownloadInfo.THREAD_READ_LENGTH))>0&&tmpLen<length){
                tmpLen+=nRead;
                tmpSaveFile.write(b,0,nRead);
            }
            System.out.println("线程 "+this.getId()+" 下载完成!下载片段["+this.start+"字节至"+(this.start+length)+"字节]");
        }catch(Exception e){
            System.out.println("线程 "+this.getId()+" 出错");
            DownloadTask task=new DownloadTask(info,start+tmpLen,length-tmpLen);
            task.start();
            DownloadProject.totalThread++;
            System.out.println("线程 "+task.getId()+" 开启恢复 从 "+(start+tmpLen)+" ");
        }finally{
        	try {
				input.close();
				tmpSaveFile.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	DownloadProject.totalThread--;
        }


    }

    public long getLength() {
        return length;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public DownloadInfo getInfo() {
        return info;
    }

    public void setInfo(DownloadInfo info) {
        this.info = info;
    }

    public long getStart() {
        return start;
    }

    public void setStart(long start) {
        this.start = start;
    }

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics