java 多线程分段下载

java 多线程分段下载

介绍

使用java 多线程下载,当前只是一个demo,还没进行对比测试,目前看速度确实要快一些

实现和简单就是启用多个现成分段下载,最后再组合在一起

完整代码

原本是下载tomcat10的,但是我本地jdk不符,最后下载的8


import lombok.SneakyThrows;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AllDown {
   // static String downUrl = "https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.19/src/apache-tomcat-10.1.19-src.zip";
    static String downUrl = "https://dlcdn.apache.org/tomcat/tomcat-8/v8.5.99/bin/apache-tomcat-8.5.99-windows-x64.zip";
    public static void main(String[] args) throws IOException {
        long t1 = System.currentTimeMillis();
        URL url = new URL(downUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept-Encoding", "identity");
        long size =  conn.getContentLengthLong();
        System.out.println("大小" + size);
        Map<Integer, byte[]> map = new HashMap<>();
        long start = -1;
        long end = -1;
        int index = 0;
        List<Thread> list = new ArrayList<>();
        while (end < size) {
            start = end;
            end += 1000000;
            if (end >= size) {
                end = size;
            }
            System.out.println("start" + start + "," + "end" + end);
            list.add(new Thread(new Run(start+1,end,index,map)));
            index++;
        }
        list.forEach(e->e.start());
        list.forEach(e-> {
            try {
                e.join();
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        });

        System.out.println("map " + map);
        OutputStream out = new FileOutputStream("tomcat.zip");
        for(int i=0;i<map.size();i++){
            out.write(map.get(i));
        }
        out.flush();
        out.close();
        long t2 = System.currentTimeMillis();
        System.out.println("耗费时间" + (t2-t1) + "ms");

    }

}

class Run implements Runnable {

    long start;
    long end;
    Integer index;
    Map<Integer, byte[]> map;

    public Run(long start,
               long end,
               Integer index,
               Map<Integer, byte[]> map) {
        this.start = start;
        this.end = end;
        this.index = index;
        this.map = map;

    }

    @SneakyThrows
    @Override
    public void run() {
        URL url = new URL(AllDown.downUrl);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        InputStream in = conn.getInputStream();
        int len = -1;
        byte[] buff = new byte[2048];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(buff)) > -1) {
            out.write(buff,0,len);
        }
        out.flush();
        map.put(index, out.toByteArray());
        out.close();
        in.close();
    }
}

日志

大小12482200
start-1,end999999
start999999,end1999999
start1999999,end2999999
start2999999,end3999999
start3999999,end4999999
start4999999,end5999999
start5999999,end6999999
start6999999,end7999999
start7999999,end8999999
start8999999,end9999999
start9999999,end10999999
start10999999,end11999999
start11999999,end12482200
map {0=[B@7e9131d5, 1=[B@2e1d27ba, 2=[B@61d6015a, 3=[B@2525ff7e, 4=[B@524d6d96, 5=[B@152aa092, 6=[B@44a7bfbc, 7=[B@4ef37659, 8=[B@776b83cc, 9=[B@37858383, 10=[B@4e268090, 11=[B@1bb266b3, 12=[B@306cf3ea}
耗费时间33111ms

本地浏览器下载
在这里插入图片描述

还是有一些提升的

最后

解压打开后
在这里插入图片描述

  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java实现FTP大文件多线程分段下载的代码示例: import java.io.*; import java.net.*; import java.util.concurrent.*; public class FTPDownload { private static final int NUM_THREADS = 10; public static void main(String[] args) { String ftpServer = "ftp.example.com"; String ftpFilePath = "/path/to/file"; String localFilePath = "/path/to/local/file"; ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); try { URL url = new URL("ftp://" + ftpServer + ftpFilePath); URLConnection connection = url.openConnection(); long fileSize = connection.getContentLengthLong(); RandomAccessFile localFile = new RandomAccessFile(localFilePath, "rw"); localFile.setLength(fileSize); localFile.close(); long chunkSize = fileSize / NUM_THREADS; long remainder = fileSize % NUM_THREADS; CountDownLatch latch = new CountDownLatch(NUM_THREADS); for (int i = 0; i < NUM_THREADS; i++) { long startByte = i * chunkSize; long endByte = (i == NUM_THREADS - 1) ? fileSize - 1 : startByte + chunkSize - 1; executor.execute(new DownloadTask(ftpServer, ftpFilePath, localFilePath, startByte, endByte, latch)); } latch.await(); } catch (Exception e) { e.printStackTrace(); } finally { executor.shutdown(); } } private static class DownloadTask implements Runnable { private String ftpServer; private String ftpFilePath; private String localFilePath; private long startByte; private long endByte; private CountDownLatch latch; public DownloadTask(String ftpServer, String ftpFilePath, String localFilePath, long startByte, long endByte, CountDownLatch latch) { this.ftpServer = ftpServer; this.ftpFilePath = ftpFilePath; this.localFilePath = localFilePath; this.startByte = startByte; this.endByte = endByte; this.latch = latch; } public void run() { try { URL url = new URL("ftp://" + ftpServer + ftpFilePath); URLConnection connection = url.openConnection(); connection.setRequestProperty("Range", "bytes=" + startByte + "-" + endByte); InputStream input = connection.getInputStream(); RandomAccessFile localFile = new RandomAccessFile(localFilePath, "rw"); localFile.seek(startByte); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) != -1) { localFile.write(buffer, 0, bytesRead); } input.close(); localFile.close(); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } } } 笑话:为什么程序员总是说计算机只能做0和1的事情?因为他们从来都没有试过按下esc键!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值