亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Java多線程下載文件實現案例詳解

瀏覽:2日期:2022-09-01 13:47:44

原理解析:

利用RandomAccessFile在本地創建一個隨機訪問文件,文件大小和服務器要下載的文件大小相同。 根據線程的數量(假設有三個線程),服務器的文件三等分,并把我們在本地創建的文件同樣三等分,每個線程下載自己負責的部分,到相應的位置即可。

示例圖:

Java多線程下載文件實現案例詳解

代碼如下

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; //每個現成下載的開始位置 int endIndex = (i + 1) * blockSize - 1;// 每個線程的結束位置 if (i == threadCount - 1) { //最后一個線程 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) { } } }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 最新亚洲精品国自产在线 | 久久七| 国模大胆偷拍在线视频 | 国产精品久久国产三级国电话系列 | 伦伦影院精品一区 | 国产三级成人 | 毛片线看免费观看 | 国产91欧美 | 亚洲福利在线观看 | 1000部国产成人免费视频 | 99久久综合给久久精品 | 日本黄色小视频在线观看 | 蕾丝视频成人★在线观看 | 在线精品福利视频你懂的 | 日本高清xxx免费视频 | 国产五月婷婷 | 国产一有一级毛片视频 | 欧美成人免费在线观看 | 久草在线观看福利视频 | 性视频一区二区三区免费 | 日本高清免费不卡毛片 | 成人免费一级毛片在线播放视频 | 一区二区在线观看高清 | 青青操国产 | 黄 色 片 在 线 看 | 国产大伊香蕉精品视频 | 香蕉网站在线观看 | a免费毛片在线播放 | 国产人妖视频一区在线观看 | 亚洲精品视频在线 | 国内国语一级毛片在线视频 | 久久国产精品免费专区 | 极品美女aⅴ高清在线观看 极品美女一级毛片 | 欧美黄网站免费观看 | 好吊色综合网天天高清 | 亚洲一区二区三区日本久久九 | 亚洲国产日韩在线人成蜜芽 | 全黄a一级毛片 | 日韩欧美中 | 日韩中文字幕第一页 | 一区二区三区精品国产欧美 |