基于Http的文件断点续传实现
创始人
2024-05-31 22:44:21
0

1:断点续传的介绍
客户端软件断点续传指的是在下载或上传时,将下载或上传任务(一个文件或一个压缩包)人为的划分为几个部分,每一个部分采用一个线程进行上传或下载,如果碰到网络故障,可以从已经上传或下载的部分开始继续上传下载未完成的部分,而没有必要从头开始上传下载。从而达到让用户节省时间,提高速度的目的。

2:断点续传的环境要求
如果是基于http请求与响应实现的断点续传,需要服务器支持"响应一部分"数据的功能;(本案例采用的是tomcat7服务器,而tomcat7服务器是支持这个功能的)

在客户端需要使用RandomAccessFile类对文件任意位置的数据进行随机读写操作;

3:java的RandomAccessFile类介绍
java的API中对RandomAccessFile类的解释如下:

我对RandomAccessFile类的理解是:RandomAccessFile类是java提供的一个可以用于随机读写文件内容的类,我们可以对RandomAccessFile类关联的文件中的任意位置和任意大小的数据进行任意的读写操作;因此要想完成文件的断点续传操作,该类的使用是必不可少的!

4:断点续传的基本实现思路

5:断点续传的代码实现
基础环境搭建:

创建WEB的maven工程;

引入maven的tomcat7插件;

在webapp目录下存放多个文件,以备测试断点续传下载使用;

java客户端代码实现:

public class MyDownLoadClient {
public static String urlpath = “http://127.0.0.1:80/”;
private static int threadCount = 5;

public static void main(String[] args) throws Exception {// 让用户输入要下载的文件名称Scanner sc = new Scanner(System.in);System.out.println("请输入要下载的文件名称:");String file = sc.next();urlpath = urlpath.concat(file);// 获取文件总大小URL url = new URL(urlpath);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(2000);int responseCode = conn.getResponseCode();if (responseCode == 200) {int contentLength = conn.getContentLength();System.out.println("length" + contentLength);int part = contentLength / threadCount;// 读配置文件ConcurrentHashMap map = new ConcurrentHashMap<>();CountDownLatch count;InputStream in = MyDownLoadClient.class.getClassLoader().getResourceAsStream(file + ".properties");if (in != null) {// 说明该文件不是第一次下载,需要断点续传Properties p = new Properties();p.load(in);in.close();Set keys = p.stringPropertyNames();count = new CountDownLatch(keys.size());for (String key : keys) {String value = p.getProperty(key);String[] arr = value.split(",");long start = Long.parseLong(arr[0]);long end = Long.parseLong(arr[1]);map.put(key,value);new DownloadThread(start, end, key, map, count, file).start();}p.clear();p = null;} else {count = new CountDownLatch(threadCount);// 说明该文件是第一次下载,直接下载即可for (int i = 0; i < threadCount; i++) {long startIndex = i * part; //每个线程起始下载位置long endIndex = (i + 1) * part;//每个线程的结束位置if (i == threadCount - 1) {//最后一个线程的结束位置endIndex = contentLength;}map.put( String.valueOf(i),startIndex+","+endIndex);new DownloadThread(startIndex, endIndex, String.valueOf(i), map, count, file).start();}}// 等待任务完成,删除配置文件count.await();new File(MyDownLoadClient.class.getClassLoader().getResource("").getPath(),file + ".properties").delete();System.out.println("==========================下载任务完成==========================");} else {System.out.println("连接服务器失败...请检查服务器是否畅通及资源路径是否正确...");}
}

}
下载任务的线程代码实现:

class DownloadThread extends Thread {
private long startIndex;
private long endIndex;
private String threadId;
private ConcurrentHashMap map;
private CountDownLatch count;
//private long subTotal = 0;
private String fileName;

public DownloadThread(long startIndex, long endIndex, String threadId, ConcurrentHashMap map, CountDownLatch count, String fileName) {this.startIndex = startIndex;this.endIndex = endIndex;this.threadId = threadId;this.map = map;this.count = count;this.fileName = fileName;
}@Override
public void run() {try {URL url = new URL(MyDownLoadClient.urlpath);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(fileName, "rw");rafAccessFile.seek(startIndex);InputStream is = conn.getInputStream();int len = -1;byte[] buffer = new byte[1024];Random r = new Random();while ((len = is.read(buffer)) != -1) {FileOutputStream fout = new FileOutputStream(this.getClass().getClassLoader().getResource("").getPath()+""+fileName + ".properties");try {//模拟意外情况导致下载中断的代码/*if (r.nextInt(2) == 0) {int i = 1 / 0;}*/rafAccessFile.write(buffer, 0, len);startIndex += len;map.put(threadId, startIndex + "," + endIndex);} catch (Exception e) {e.printStackTrace();throw new RuntimeException();} finally {Set> entries = map.entrySet();for (Map.Entry entry : entries) {fout.write((entry.getKey() + "=" + entry.getValue() + "rn").getBytes());}fout.close();}}rafAccessFile.close();System.out.println("线程" + threadId + "下载完成");System.gc();}count.countDown();} catch (Exception e) {e.printStackTrace();System.gc();}
}

}
6:功能测试

  1. 在web工程中提前准备好要下载的文件;(任意类型,任意文件均可,本项目以三个api举例)

  2. 启动tomcat服务器;(已经设置虚拟目录为 “/” 端口号为 “80”)

  3. 启动java主程序类(MyDownLoadClient),输入要下载的文件名;

  4. 可以通过打开线程任务中模拟意外情况的代码,让下载出现意外,当程序出现意外后,配置文件不会删除,且会记录下所有线程已经完成的下载量,以便于下次执行下载任务的时候,可以在此基础上继续完成下载任务;

  5. 关闭模拟意外的代码,重新执行程序,直到文件顺利下载完成,程序会自动删除对应的配置文件;

7:功能实现总结
断点续传最核心的思想就是利用RandomAccessFile类将一个大文件配合多线程拆分成多个片段进行读写,最终将多个线程读写的结果再合并成1个大文件即可;1:断点续传的介绍
客户端软件断点续传指的是在下载或上传时,将下载或上传任务(一个文件或一个压缩包)人为的划分为几个部分,每一个部分采用一个线程进行上传或下载,如果碰到网络故障,可以从已经上传或下载的部分开始继续上传下载未完成的部分,而没有必要从头开始上传下载。从而达到让用户节省时间,提高速度的目的。

2:断点续传的环境要求
如果是基于http请求与响应实现的断点续传,需要服务器支持"响应一部分"数据的功能;(本案例采用的是tomcat7服务器,而tomcat7服务器是支持这个功能的)

在客户端需要使用RandomAccessFile类对文件任意位置的数据进行随机读写操作;

3:java的RandomAccessFile类介绍
java的API中对RandomAccessFile类的解释如下:

我对RandomAccessFile类的理解是:RandomAccessFile类是java提供的一个可以用于随机读写文件内容的类,我们可以对RandomAccessFile类关联的文件中的任意位置和任意大小的数据进行任意的读写操作;因此要想完成文件的断点续传操作,该类的使用是必不可少的!

4:断点续传的基本实现思路

5:断点续传的代码实现
基础环境搭建:

创建WEB的maven工程;

引入maven的tomcat7插件;

在webapp目录下存放多个文件,以备测试断点续传下载使用;

java客户端代码实现:

public class MyDownLoadClient {
public static String urlpath = “http://127.0.0.1:80/”;
private static int threadCount = 5;

public static void main(String[] args) throws Exception {// 让用户输入要下载的文件名称Scanner sc = new Scanner(System.in);System.out.println("请输入要下载的文件名称:");String file = sc.next();urlpath = urlpath.concat(file);// 获取文件总大小URL url = new URL(urlpath);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(2000);int responseCode = conn.getResponseCode();if (responseCode == 200) {int contentLength = conn.getContentLength();System.out.println("length" + contentLength);int part = contentLength / threadCount;// 读配置文件ConcurrentHashMap map = new ConcurrentHashMap<>();CountDownLatch count;InputStream in = MyDownLoadClient.class.getClassLoader().getResourceAsStream(file + ".properties");if (in != null) {// 说明该文件不是第一次下载,需要断点续传Properties p = new Properties();p.load(in);in.close();Set keys = p.stringPropertyNames();count = new CountDownLatch(keys.size());for (String key : keys) {String value = p.getProperty(key);String[] arr = value.split(",");long start = Long.parseLong(arr[0]);long end = Long.parseLong(arr[1]);map.put(key,value);new DownloadThread(start, end, key, map, count, file).start();}p.clear();p = null;} else {count = new CountDownLatch(threadCount);// 说明该文件是第一次下载,直接下载即可for (int i = 0; i < threadCount; i++) {long startIndex = i * part; //每个线程起始下载位置long endIndex = (i + 1) * part;//每个线程的结束位置if (i == threadCount - 1) {//最后一个线程的结束位置endIndex = contentLength;}map.put( String.valueOf(i),startIndex+","+endIndex);new DownloadThread(startIndex, endIndex, String.valueOf(i), map, count, file).start();}}// 等待任务完成,删除配置文件count.await();new File(MyDownLoadClient.class.getClassLoader().getResource("").getPath(),file + ".properties").delete();System.out.println("==========================下载任务完成==========================");} else {System.out.println("连接服务器失败...请检查服务器是否畅通及资源路径是否正确...");}
}

}
下载任务的线程代码实现:

class DownloadThread extends Thread {
private long startIndex;
private long endIndex;
private String threadId;
private ConcurrentHashMap map;
private CountDownLatch count;
//private long subTotal = 0;
private String fileName;

public DownloadThread(long startIndex, long endIndex, String threadId, ConcurrentHashMap map, CountDownLatch count, String fileName) {this.startIndex = startIndex;this.endIndex = endIndex;this.threadId = threadId;this.map = map;this.count = count;this.fileName = fileName;
}@Override
public void run() {try {URL url = new URL(MyDownLoadClient.urlpath);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(fileName, "rw");rafAccessFile.seek(startIndex);InputStream is = conn.getInputStream();int len = -1;byte[] buffer = new byte[1024];Random r = new Random();while ((len = is.read(buffer)) != -1) {FileOutputStream fout = new FileOutputStream(this.getClass().getClassLoader().getResource("").getPath()+""+fileName + ".properties");try {//模拟意外情况导致下载中断的代码/*if (r.nextInt(2) == 0) {int i = 1 / 0;}*/rafAccessFile.write(buffer, 0, len);startIndex += len;map.put(threadId, startIndex + "," + endIndex);} catch (Exception e) {e.printStackTrace();throw new RuntimeException();} finally {Set> entries = map.entrySet();for (Map.Entry entry : entries) {fout.write((entry.getKey() + "=" + entry.getValue() + "rn").getBytes());}fout.close();}}rafAccessFile.close();System.out.println("线程" + threadId + "下载完成");System.gc();}count.countDown();} catch (Exception e) {e.printStackTrace();System.gc();}
}

}
6:功能测试

  1. 在web工程中提前准备好要下载的文件;(任意类型,任意文件均可,本项目以三个api举例)

  2. 启动tomcat服务器;(已经设置虚拟目录为 “/” 端口号为 “80”)

  3. 启动java主程序类(MyDownLoadClient),输入要下载的文件名;

  4. 可以通过打开线程任务中模拟意外情况的代码,让下载出现意外,当程序出现意外后,配置文件不会删除,且会记录下所有线程已经完成的下载量,以便于下次执行下载任务的时候,可以在此基础上继续完成下载任务;

  5. 关闭模拟意外的代码,重新执行程序,直到文件顺利下载完成,程序会自动删除对应的配置文件;

7:功能实现总结
断点续传最核心的思想就是利用RandomAccessFile类将一个大文件配合多线程拆分成多个片段进行读写,最终将多个线程读写的结果再合并成1个大文件即可;

相关内容

热门资讯

安卓系统打游戏推荐,一触即达! 你有没有发现,现在手机游戏越来越好玩了?不管是休闲小游戏还是大型MMORPG,都能在手机上畅玩。但是...
开店宝系统和安卓,助力商家轻松... 你有没有想过,开店也能变得如此轻松?没错,就是那个神奇的“开店宝系统”,它可是安卓平台上的一大神器呢...
安卓平板装早教机系统,安卓平板... 你有没有想过,家里的安卓平板除了刷剧、玩游戏,还能变成一个超级早教机呢?没错,就是那种能让孩子从小接...
电脑装安卓系统好处,电脑装安卓... 你有没有想过,你的电脑装上安卓系统会有什么神奇的变化呢?想象一台原本只能处理文档和PPT的电脑,突然...
HTC莫扎特刷安卓系统,畅享全... 你有没有听说过HTC莫扎特这款手机?最近,它可是刷爆了安卓系统爱好者们的眼球呢!今天,就让我带你一起...
安卓系统的致命漏洞,揭秘潜在安... 你知道吗?最近安卓系统可是闹出了一个大新闻,一个致命的漏洞让无数用户都紧张兮兮的。咱们就来聊聊这个事...
安卓的系统文件在哪,安卓系统文... 你有没有想过,你的安卓手机里那些神秘的系统文件都藏在哪个角落呢?别急,今天就来带你一探究竟,让你对这...
公认最好的安卓系统,揭秘公认最... 你有没有想过,为什么安卓手机那么受欢迎?是不是因为那个公认最好的安卓系统?没错,今天咱们就来聊聊这个...
安卓系统默认音量调整,轻松设置... 你有没有发现,每次拿起手机,那个默认的音量调整按钮总是那么默默无闻地躺在那里?今天,就让我带你一探究...
照片怎样导出安卓系统,一键导出... 你有没有遇到过这种情况:手机里存了好多美美的照片,想分享给朋友或者保存到电脑上,却发现导出照片到安卓...
什么电视支持安卓系统,解锁智能... 你有没有想过,家里的电视是不是也能像手机一样,随时随地下载各种应用,畅享网络世界呢?没错,现在很多电...
鸿蒙系统投屏安卓系统电视,开启... 亲爱的读者们,你是否曾想过,家里的安卓电视也能享受到鸿蒙系统的魅力呢?没错,今天就要来聊聊这个让人眼...
安卓系统如何连手柄,安卓系统下... 你有没有想过,在安卓系统上玩游戏的时候,如果能够用上游戏手柄,那该有多爽啊!想象手指轻轻一按,游戏角...
安卓打包当前系统rom,基于安... 你有没有想过,手机里的安卓系统其实就像是一个个精心打造的城堡,而ROM就像是这座城堡的装修风格。今天...
索爱售后安卓系统,索爱售后安卓... 你有没有遇到过手机售后的问题呢?尤其是那些安卓系统的手机,有时候出了点小状况,真是让人头疼。今天,咱...
安卓7.0系统速度咋样,速度与... 你有没有发现,自从手机更新到安卓7.0系统后,感觉整个手机都焕然一新了呢?今天,就让我来给你详细聊聊...
安卓文件系统隔离,Androi... 你知道吗?在安卓的世界里,有一个神奇的小秘密,那就是安卓文件系统隔离。听起来是不是有点高大上?别急,...
电脑板安卓系统下载,轻松实现多... 你有没有想过,你的电脑板突然间变得如此强大,竟然能运行安卓系统?没错,这就是科技的魅力!今天,就让我...
安卓系统双开app排行,热门双... 安卓系统双开App排行大揭秘在数字化时代,手机已经成为我们生活中不可或缺的一部分。而安卓系统,作为全...
安卓原生系统谁在开发,谷歌主导... 你有没有想过,那个陪伴你每天刷抖音、玩游戏、办公的安卓系统,究竟是谁在背后默默开发呢?今天,就让我带...