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

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

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

瀏覽:3日期: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
相關文章:
主站蜘蛛池模板: 国产综合精品久久久久成人影 | 亚欧成人一区二区 | 在线观看国产精品日本不卡网 | 国产51页| 狠狠干影视 | 日本黄色录像 | 国产精品网站在线进入 | 成人欧美日韩高清不卡 | 国产福利不卡视频在免费播放 | 看欧美的一级毛片 | 男生j桶进女人p又色又爽又黄 | 成人永久免费 | 亚洲色图视频在线观看 | 午夜一区二区三区 | 香蕉视频免费网站 | 黄播视频 | 亚洲综合免费 | 日韩高清一级 | 欧美一级大片免费看 | 日韩精品一区二区三区免费视频 | 91看视频 | 久久这里只有精品23 | 99久久精品费精品国产一区二区 | 综合久青草视频 | 黄网址在线观看 | 午夜色a大片在线观看免费 午夜色图 | 久久国产这里只精品免费 | 最新亚洲国产有精品 | 亚洲精品一区二区四季 | 免费看a | 毛片一级毛片 | 日本高清色视频在线观看免费 | 高h猛烈做哭bl壮汉受小说 | 国产乡下三级全黄三级带 | 青青伊人网 | 黄网站免费视频 | 国产精品不卡在线观看 | 五月天婷婷久久 | 国产初高中生厕所小便 | 中文字幕一区二区视频 | 黄色录像一级片 |