java实现多线程文件的断点续传

 更新时间:2022年06月24日 09:22:38   作者:qq_38844040  
这篇文章主要为大家详细介绍了java实现多线程文件的断点续传,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

java文件的多线程断点续传大致原理,供大家参考,具体内容如下

谈到文件断点续传那么就离不开java.io.RandomAcessFile HttpUrlConnection类

大致思路如下:

1、HttpUrlConnection去请求服务器 获得文件的长度con.getContentLength()
2、创建一个空的RandomAcessFile来接收,并且指定刚刚获取的长度setLength
3、开启N个线程 计算每个线程需要下载的长度
4、获取之前先去看看下载的进度保存文件是否存在 如果存在就从文件里获取已经下载的进度
5、开始文件下载
6、临时文件的删除 资源的关闭

下面贴出完整代码

package demo;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

class MultiDownloaFile {
    public static final String path = "http://192.168.217.1:8080/androidsimpleserver/HTTP.pdf";
    public static final int TOTAL_THREAD_COUNT = 3;
    public static int runningThreadCount = 0;

    public static void main(String[] args) {
        try {
            long start = System.currentTimeMillis();
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if (code == 200) {
                int length = conn.getContentLength();
                System.out.println("file length:" + length);
                //create  a  null  file  to  save  its  length
                RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw");
                raf.setLength(length);
                raf.close();
                //parse  every  thread  that  they  need  how  much  room  to  download
                int blockSize = length / TOTAL_THREAD_COUNT;
                System.out.println("every block size:" + blockSize);
                runningThreadCount = TOTAL_THREAD_COUNT;
                for (int threadId = 0; threadId < TOTAL_THREAD_COUNT; threadId++) {
                    int startPosition = threadId * blockSize;
                    int endPosition = (threadId + 1) * blockSize - 1;
                    if (threadId == (TOTAL_THREAD_COUNT - 1)) {
                        endPosition = length - 1;
                    }
                    System.out.println("thread::" + threadId + " download range:" + startPosition + "~~" + endPosition);
                    //start thread  to  download
                    new DownloadThread(threadId, startPosition, endPosition).start();
                }
            } else {
                System.out.println(" connection  error ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从网络路径获取文件名
     *
     * @param path 网络路径
     * @return 文件名
     */
    private static String getDownloadFileName(String path) {
        return path.substring(path.lastIndexOf("/") + 1);
    }

    /**
     * 下载文件的线程
     */
    private static class DownloadThread extends Thread {
        /**
         * 线程id
         */
        private int threadId;

        /**
         * 当前线程下载的起始位置
         */
        private int startPosition;

        /**
         * 当前线程下载的终止位置
         */
        private int endPosition;

        public DownloadThread(int threadId, int startPosition, int endPosition) {
            this.threadId = threadId;
            this.startPosition = startPosition;
            this.endPosition = endPosition;
        }

        @Override
        public void run() {
            System.out.println("thread:" + threadId + " begin working");
            // lest thread download it's self range data
            try {

                File finfo = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt");
//                断点续传
                if (finfo.exists() && finfo.length() > 0) {
                    System.out.println(" 断点续传开始");
                    FileInputStream fis = new FileInputStream(finfo);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    String lastPosition = br.readLine();
                    // This thread download data before times;
                    int intLastPosition = Integer.parseInt(lastPosition);
                    startPosition = intLastPosition;
                    fis.close();
                }

                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                System.out.println("begin and end:" + threadId + " range of download: " + startPosition + "~~" + endPosition);
                conn.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);
                // Download Resource from server
                int code = conn.getResponseCode();
                if (code == 206) {
                    InputStream is = conn.getInputStream();
//                    RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw");
                    RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw");

                    // vary important, position of begin to write
                    raf.seek(startPosition);
                    byte[] buffer = new byte[1024 * 100];
                    int len = -1;
                    int total = 0; // downloaded data of current thread in this times;
                    while ((len = is.read(buffer)) != -1) {
                        raf.write(buffer, 0, len);
                        // record position of current thread to downloading
                        total += len;
                        RandomAccessFile inforaf = new RandomAccessFile(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt", "rwd");
                        // save position of current thread
                        inforaf.write(String.valueOf(startPosition + total).getBytes());
                        inforaf.close();
                    }
                    is.close();
                    raf.close();
                    System.out.println("thread:" + threadId + " download complete...");
                } else {
                    System.out.println("request download failed.");
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                synchronized (MultiDownloaFile.class) {
                    runningThreadCount--;
                    if (runningThreadCount <= 0) {
                        System.out.println("  all  multi thread download complete.   success!!!");
                        for (int i = 0; i < TOTAL_THREAD_COUNT; i++) {
                            File finfo = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + i + ".txt");
                            System.out.println(finfo.delete());
                        }
                    }
                }
            }
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 浅析Spring工厂的反射和配置文件

    浅析Spring工厂的反射和配置文件

    这篇文章主要介绍了浅析Spring工厂的反射和配置文件,spring是通过反射和配置文件的方式来获取 JavaBean 对象,需要的朋友可以参考下
    2023-04-04
  • Spring Boot 功能整合的实现

    Spring Boot 功能整合的实现

    Spring Boot生态丰富,集成也不算困难。本文简单的介绍下功能整合的步骤,最后提供一个具体的实现例子,学习Spring Boot的同学可以参考下
    2021-05-05
  • springboot集成RestTemplate及常见的用法说明

    springboot集成RestTemplate及常见的用法说明

    这篇文章主要介绍了springboot集成RestTemplate及常见的用法说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • 重新对Java的类加载器的学习方式

    重新对Java的类加载器的学习方式

    这篇文章主要介绍了重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-05-05
  • springboot登陆过滤功能的实现代码

    springboot登陆过滤功能的实现代码

    这篇文章主要介绍了springboot登陆过滤功能的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • Java JConsole远程连接配置案例详解

    Java JConsole远程连接配置案例详解

    这篇文章主要介绍了Java JConsole远程连接配置案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Java使用新浪微博API开发微博应用的基本方法

    Java使用新浪微博API开发微博应用的基本方法

    这篇文章主要介绍了Java使用新浪微博API开发微博应用的基本方法,文中还给出了一个不使用任何SDK实现Oauth授权并实现简单的发布微博功能的实现方法,需要的朋友可以参考下
    2015-11-11
  • JPA设置默认字段及其长度详解

    JPA设置默认字段及其长度详解

    JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。本文主要介绍了JPA如何设置默认字段及其长度,感兴趣的同学可以了解一下
    2021-12-12
  • SpringBoot基于Actuator远程关闭服务

    SpringBoot基于Actuator远程关闭服务

    这篇文章主要介绍了SpringBoot基于Actuator远程关闭服务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Springboot如何同时装配两个相同类型数据库

    Springboot如何同时装配两个相同类型数据库

    这篇文章主要介绍了Springboot如何同时装配两个相同类型数据库,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11

最新评论