多线程下载文件

多线程下载文件

近期上传和下载的代码没少写,毕竟公司业务需要和图片视频打交道。就在今天脑海里忽然想到(没错我是小垃圾今天才想到多线程下载)百度网盘破解插件多线程下载提高下载速度,有了一点点灵感捣鼓小半天测试总结一下。放代码之前请感受一下我的笑里藏刀:哈哈哈哈哈哈刀哈哈哈哈哈哈

RandomAccessFile类实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组,输入输出操作从文件指针开始,文件指针可以通过 getFilePointer 方法读取,并通过 seek 方法设置。

package com.zoe;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * All rights Reserved.
 * title:com.zoe
 * ClassName:DownloadThread
 * Description:(请用一句话描述这个类的作用)
 * Compony:fh
 * author:Rengar
 * date:2020/12/21
 * version:1.0
 * 注意:本内容仅限于公司内部传阅,禁止外泄以及用于其他的商业目
 */
public class DownloadThread implements Runnable {
    private String urlLocation; //资源文件路径
    private String filePath; //本地文件路径
    private long start; //文件字节指针开始
    private long end; //文件字节指针结束
    private Integer threadId; //线程编号

    public DownloadThread(String urlLocation, String filePath, long start, long end, Integer threadId) {
        this.urlLocation = urlLocation;
        this.filePath = filePath;
        this.start = start;
        this.end = end;
        this.threadId = threadId;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        RandomAccessFile randomAccessFile = null;
        try {
            HttpURLConnection httpUrlConn = getHttpUrlConn();
            httpUrlConn.setRequestProperty("Range","bytes=" + start + "-" + end);

            File dir = new File(filePath.substring(0, filePath.lastIndexOf("\\")));
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(filePath);
            randomAccessFile = new RandomAccessFile(file, "rw");
            //设置文件指针的写入位置
            randomAccessFile.seek(start);
            inputStream = httpUrlConn.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                randomAccessFile.write(bytes,0,len);
            }
            System.out.println("线程任务" + threadId + "下载任务完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private HttpURLConnection getHttpUrlConn() throws IOException {
        HttpURLConnection urlConnection = null;
        if (!"".equals(urlLocation) && urlLocation != null) {
            URL url = new URL(urlLocation);
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setReadTimeout(20000);
            urlConnection.setRequestMethod("GET");
        }
        return urlConnection;
    }
}

线程任务加入执行

package com.zoe;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * All rights Reserved.
 * title:com.zoe
 * ClassName:DownloadThreadPool
 * Description:(请用一句话描述这个类的作用)
 * Compony:fh
 * author:Rengar
 * date:2020/12/21
 * version:1.0
 * 注意:本内容仅限于公司内部传阅,禁止外泄以及用于其他的商业目
 */
public class DownloadThreadPool {

    /**
     * 下载执行
     * @param urlLocation 资源文件路径
     * @param filePath 下载的本地路径
     * @param threadCount 开启的线程数量
     * @throws IOException
     */
    public static void downloadExecute(String urlLocation,String filePath,Integer threadCount) throws IOException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //获取资源文件的总长度
        long longth = getLongth(urlLocation);
        System.out.println(longth);
        for (int i = 0; i < threadCount; i++) {
            long start = i * longth / threadCount;
            long end = (i + 1) * longth / threadCount - 1;
            if (i == threadCount - 1) {
                end = longth;
            }
            System.out.println(start + "-----------" + end);
            DownloadThread downloadThread = new DownloadThread(urlLocation, filePath, start, end, i + 1);
            threadPool.execute(downloadThread);
        }
        threadPool.shutdown();

    }

    /**
     * 获取资源文件字节长度
     * @param urlLocation 资源文件路径
     * @return
     * @throws IOException
     */
    private static long getLongth(String urlLocation) throws IOException {
        long longth = 0;
        if (!"".equals(urlLocation) && urlLocation != null) {
            URL url = new URL(urlLocation);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setReadTimeout(5000);
            urlConnection.setRequestMethod("GET");
            longth = urlConnection.getContentLengthLong();
        }
        return longth;
    }
}

测试类

package com.zoe;

import java.io.IOException;

public class DownloadTest {
    public static void main(String[] args) {
        try {
            DownloadThreadPool.downloadExecute("http://182.92.192.xxx/xxx/video/2020.mp4","D:\\hhh\\2020.mp4",10);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值