Java多線程下載文件實(shí)現(xiàn)案例詳解
原理解析:
利用RandomAccessFile在本地創(chuàng)建一個(gè)隨機(jī)訪問文件,文件大小和服務(wù)器要下載的文件大小相同。 根據(jù)線程的數(shù)量(假設(shè)有三個(gè)線程),服務(wù)器的文件三等分,并把我們在本地創(chuàng)建的文件同樣三等分,每個(gè)線程下載自己負(fù)責(zé)的部分,到相應(yīng)的位置即可。
示例圖:
代碼如下
import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class MutilDownload { private static String path = 'http://192.168.80.85:8080/test.doc'; private static final int threadCount = 3; public static void main(String[] args) { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod('GET'); conn.setConnectTimeout(5000); int responseCode = conn.getResponseCode(); if (responseCode == 200) {int contentLength = conn.getContentLength();System.out.println('length' + contentLength);RandomAccessFile rafAccessFile = new RandomAccessFile('test.doc', 'rw');rafAccessFile.setLength(contentLength);int blockSize = contentLength / threadCount;for (int i = 0; i < threadCount; i++) { int startIndex = i * blockSize; //每個(gè)現(xiàn)成下載的開始位置 int endIndex = (i + 1) * blockSize - 1;// 每個(gè)線程的結(jié)束位置 if (i == threadCount - 1) { //最后一個(gè)線程 endIndex = contentLength - 1; } new DownloadThread(startIndex, endIndex, i).start();} } } catch (Exception e) { } } private static class DownloadThread extends Thread { private int startIndex; private int endIndex; private int threadId; public DownloadThread(int startIndex, int endIndex, int threadId) { this.startIndex = startIndex; this.endIndex = endIndex; this.threadId = threadId; } @Override public void run() { try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod('GET');conn.setConnectTimeout(5000);conn.setRequestProperty('Range', 'bytes=' + startIndex + '-' + endIndex); //固定寫法,請求部分資源int responseCode = conn.getResponseCode(); // 206表示請求部分資源if (responseCode == 206) { RandomAccessFile rafAccessFile = new RandomAccessFile('test.doc', 'rw'); rafAccessFile.seek(startIndex); InputStream is = conn.getInputStream(); int len = -1; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { rafAccessFile.write(buffer, 0, len); } rafAccessFile.close(); System.out.println('線程' + threadId + '下載完成');} } catch (Exception e) { } } }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP設(shè)計(jì)模式中工廠模式深入詳解2. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測可用)3. CSS hack用法案例詳解4. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)8. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法9. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明10. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息
