private void multiThreadDownload(String sourcePath, String targetPathDir, String targetFileName, int threadCount) { fileSize = getFileSize(sourcePath); int blockSize = fileSize / threadCount; System.out.println(blockSize); RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File(targetPathDir, targetFileName), "rwd"); } catch (FileNotFoundException e) { e.printStackTrace(); } for (int threadId = 1; threadId <= threadCount; threadId++) { int beginIndex = (threadId - 1) * blockSize; int endIndex = threadId * blockSize - 1; if (threadId == threadCount) { endIndex = fileSize - 1; } System.out.println(beginIndex + " " + endIndex); new DownloadThread(sourcePath, beginIndex, endIndex, targetPathDir, targetFileName).start(); } } public class DownloadThread extends Thread { private String sourcePath; private int beginIndex; private int endIndex; private String targetPathDir; private String targetFileName; public DownloadThread(String sourcePath, int beginIndex, int endIndex, String targetPathDir, String targetFileName) { this.sourcePath = sourcePath; this.beginIndex = beginIndex; this.endIndex = endIndex; this.targetFileName = targetFileName; this.targetPathDir = targetPathDir; } @Override public void run() { HttpURLConnection conn = null; RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File(targetPathDir, targetFileName), "rwd"); URL url = new URL(sourcePath); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setRequestProperty("Range", "bytes=" + beginIndex + "-" + endIndex); int code = conn.getResponseCode(); if (code == 206) { InputStream is = conn.getInputStream(); raf.seek(beginIndex); int len = 0; byte[] buff = new byte[1024]; while ((len = is.read(buff)) != -1) { raf.write(buff, 0, len); } } runningThread--; } catch (IOException e) { e.printStackTrace(); }finally { if (runningThread == 0) { long endtime = System.currentTimeMillis(); long time = (endtime - beginTime) / 1000; float speed = (float)fileSize/1024/1024/time; System.out.println("over " +time + " " +speed); }else { System.out.println(runningThread); } } } } private static int getFileSize(String sourcePath) { int fileSize = 0; HttpURLConnection conn = null; try { URL url = new URL(sourcePath); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { fileSize = conn.getContentLength(); System.out.println(fileSize); } } catch (java.io.IOException e) { e.printStackTrace(); } finally { conn.disconnect(); } return fileSize; }
原文:http://www.cnblogs.com/linson0116/p/4968658.html