package com.gyarmy.testDownload; import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class ThreadDownload { private static int ThreadCount=5; private static String path = "http://www.xxxx.com/file.txt"; public static void main(String[] args) { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(20000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); if(200 == code){ int contentLength = conn.getContentLength(); System.out.println("长度:" + contentLength); //创建文件 File file = new File(getFileName(path)); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.setLength(contentLength); raf.close(); int blockSize = contentLength/ThreadCount; for(int ThreadId=0;ThreadId<ThreadCount;ThreadId++){ int startIndex = ThreadId*blockSize; int endIndex = (ThreadId+1)*blockSize-1; if(ThreadId==ThreadCount-1){ endIndex = contentLength-1; } //System.out.println("线程ID:"+ThreadId+" 下载从 "+startIndex+" 开始, 结束的位置: "+endIndex); new MyThreadDownload(ThreadId,startIndex,endIndex).start(); } } }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static class MyThreadDownload extends Thread{ private int ThreadId; private int startIndex; private int endIndex; public MyThreadDownload(int ThreadId,int startIndex,int endIndex){ this.ThreadId = ThreadId; this.startIndex = startIndex; this.endIndex = endIndex; } @Override public void run() { // TODO Auto-generated method stub super.run(); System.out.println("线程ID:"+ThreadId+" 开始下载从 "+startIndex+" 开始, 结束的位置: "+endIndex); try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(2000); conn.setRequestMethod("GET"); conn.setRequestProperty("range", "bytes="+startIndex+"-"+endIndex); int code = conn.getResponseCode(); if(206 == code){ InputStream in = conn.getInputStream(); File file = new File(getFileName(path)); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(startIndex); int len=0; byte[] buffer = new byte[1024]; while((len = in.read(buffer))>0){ raf.write(buffer, 0, len); } in.close(); raf.close(); } System.out.println("线程ID:"+ThreadId+" 下载完毕"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static String getFileName(String path) { int index = path.lastIndexOf("/"); return path.substring(index+1); } }
0则评论给“多线程下载实例测试”