日记二 断点续传

来源:互联网 发布:unity3d 麻将 编辑:程序博客网 时间:2024/05/18 00:24
import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class test {private static String path = "网址";private static int threadcount = 3;public static void main(String[] args) {try {//联网URL url = new URL(path);HttpURLConnection connection =(HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setReadTimeout(4000);int code  = connection.getResponseCode();if(code==200){//获取下载文件长度int length = connection.getContentLength();//在本地创建一样大的文件RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");file.setLength(length);int blockSize = length/threadcount;//计算每一个线程要下载的数据范围for(int i = 0 ;i<threadcount;i++){int starIndex = i*blockSize;int endIndex = (i+1)*blockSize;if(i==threadcount-1){endIndex = length -1;}//创建多个线程new DThread(starIndex, endIndex, i).start();}}} catch (Exception e) {e.printStackTrace();}}private static class DThread extends Thread {private int startIndex;private int endIndex;private int threadID;public DThread(int startIndex, int endIndex, int threadID) {super();this.startIndex = startIndex;this.endIndex = endIndex;this.threadID = threadID;}public void run() {try {URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(4000);connection.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);if(connection.getResponseCode()==206){System.out.println("xc"+startIndex+"开始下载");InputStream inputstream = connection.getInputStream();int len = -1;byte[] buffer = new byte[1024];RandomAccessFile file = new RandomAccessFile(getFileName(path), "rw");//记得seek到startIndex位置写入数据file.seek(startIndex);while((len=inputstream.read(buffer))!=-1){file.write(buffer,0,len);}file.close();System.out.println("xc"+threadID+"完成");}} catch (IOException e) {e.printStackTrace();}}}//截取文件名private static String getFileName(String path2) {String[] result = path2.split("/");return result[result.length - 1];}}

原创粉丝点击