多线程断点续传

来源:互联网 发布:小灰狼打印软件 编辑:程序博客网 时间:2024/05/16 09:52
package com.lee.download;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class Demo {public static int threadCount=3;public static int runningThread=threadCount;public static void main(String[] args) throws IOException {String path="http://169.254.199.61:8080/player.exe";URL url=new URL(path);HttpURLConnection conn=(HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int code=conn.getResponseCode(); if(code==200){ int size=conn.getContentLength(); System.out.println("文件总大小:"+size); File file=new File("player.exe"); RandomAccessFile raf=new RandomAccessFile(file, "rwd"); raf.setLength(size); raf.close();  int blockSize=size/threadCount; for(int threadID=1;threadID<=threadCount;threadID++){ int startIndex=(threadID-1)*blockSize; int endIndex=threadID*blockSize-1; if(threadID==threadCount){ endIndex=size; } System.out.println("线程"+threadID+"::"+startIndex+"-->"+endIndex);  new DownloadThread(path, threadID, startIndex, endIndex).start(); } }else{ System.out.println("服务器连接异常"); }}public static class DownloadThread extends Thread{String path;int threadID;int startIndex;int endIndex;public DownloadThread(String path,int threadID,int startIndex,int endIndex){this.path=path;this.threadID=threadID;this.startIndex=startIndex;this.endIndex=endIndex;}@Overridepublic void run() {try {File tempFile=new File(threadID+".lee");if(tempFile.exists()&& tempFile.length()>0){FileInputStream fis=new FileInputStream(tempFile);byte[] temp=new byte[1024];int leng=fis.read(temp);String downloaded=new String(temp,0,leng);int downloadedSize=Integer.parseInt(downloaded);startIndex=downloadedSize;fis.close();}URL url=new URL(path);HttpURLConnection conn=(HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);conn.setConnectTimeout(5000);int code=conn.getResponseCode();//200从服务器请求全部资源,206从服务器请求部分资源System.out.println(threadID+"-Range::"+startIndex+"-->"+endIndex);if(code==206){InputStream is=conn.getInputStream();RandomAccessFile raf=new RandomAccessFile("player.exe", "rwd");raf.seek(startIndex);int len=0;byte[] buffer=new byte[1024];int off=0;while((len=is.read(buffer))!=-1){RandomAccessFile record=new RandomAccessFile(threadID+".lee", "rwd");raf.write(buffer, 0, len);off+=len;record.write((off+startIndex+"").getBytes());record.close();//System.out.println("线程"+threadID+"已下载到:"+(off+startIndex));}is.close();raf.close();System.out.println("线程"+threadID+"下载完毕");}else{System.out.println("线程"+threadID+"下载失败");return;}} catch (Exception e) {e.printStackTrace();}finally{runningThread--;if(runningThread==0){for (int i = 1; i <=threadCount ; i++) {File file=new File(i+".lee");file.delete();}System.out.println("文件下载完毕,删除临时记录文件");}}}}}

0 0
原创粉丝点击