基于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个大文件即可;

相关内容

热门资讯

安卓系统app和ios系统的区... 你有没有发现,手机里的APP就像是个大杂烩,各有各的特色,各有各的玩法。今天,咱们就来聊聊安卓系统和...
宿迁综合办公系统安卓,便捷高效... 你有没有听说最近宿迁市推出了一款超级方便的安卓应用——宿迁综合办公系统?这可是个大新闻,让我来给你详...
小米平板4系统安卓下载,畅享智... 亲爱的数码爱好者们,你是否在寻找一款性价比超高、性能稳定的平板电脑呢?小米平板4绝对是你的不二之选!...
安卓系统易用性盘点,人性化设计... 你有没有发现,手机里的安卓系统就像一个万能的小助手,无论你是喜欢玩游戏、看视频,还是处理工作,它都能...
鸿蒙系统中出现安卓代码 鸿蒙系统中的安卓代码奇缘在当今科技飞速发展的时代,智能手机已经成为了我们生活中不可或缺的一部分。而在...
安卓系统的双开免费的,免费畅享... 《探索安卓系统的双开免费新世界》在数字化时代,智能手机已经成为我们生活中不可或缺的一部分。而在这众多...
转国外的安卓系统,探索国外安卓... 你有没有想过,让你的安卓手机体验一下国外的风味呢?想象那些国外的应用、游戏,还有那独特的系统设置,是...
安卓系统韩国能用吗,兼容性与使... 你有没有想过,如果你去韩国旅游或者工作,你的安卓手机还能不能用呢?这个问题可真是让人好奇啊!毕竟,每...
安卓手机系统占多少储存 你有没有发现,你的安卓手机越来越慢了?是不是觉得存储空间不够用,连个新应用都装不下?别急,今天就来给...
freemeos是安卓系统吗,... 你有没有听说过freemeOS这个系统?是不是好奇它是不是安卓系统呢?今天,我就来给你揭秘这个神秘的...
安卓系统其他应用耗电大,那些默... 手机电量总是不够用?是不是觉得安卓系统的其他应用耗电特别大?别急,今天就来给你揭秘这个谜团,让你手机...
华为os系统怎么换安卓系统,轻... 你有没有想过,你的华为手机里那个自家的OS系统,突然间想换换口味,试试安卓的精彩世界呢?别急,今天就...
诺基亚回用安卓系统吗,新篇章的... 你有没有听说最近的大消息?诺基亚,那个曾经手机界的巨头,竟然有可能会重新启用安卓系统!这可不是开玩笑...
安卓软件开发考勤系统 你有没有想过,在忙碌的安卓软件开发工作中,如何轻松管理团队考勤呢?别急,今天就来给你揭秘一款特别实用...
炉石传说安卓系统要求,解锁全新... 亲爱的玩家们,你是否已经迫不及待地想要在安卓设备上畅玩《炉石传说》了呢?别急,在这之前,你得先确保你...
安卓手机刷掌阅系统 你有没有想过,你的安卓手机可以变成一个掌阅小能手呢?没错,就是那种随时随地都能畅读各种电子书的掌阅系...
飞车手游ios系统跟安卓系统,... 你有没有发现,最近手机上的一款飞车手游特别火呢?这款游戏不仅画面精美,操作流畅,而且玩法多样,吸引了...
安卓平板显示系统不兼容,安卓平... 你有没有遇到过这种情况?买了一款心仪的安卓平板,满怀期待地想要体验各种精彩应用,结果却发现有些应用显...
安卓系统安装破解app病毒,安... 你知道吗?在安卓系统上安装破解版的APP,听起来是不是有点刺激?但别高兴得太早,这背后可是隐藏着不少...
安卓版桌面操作系统,探索安卓桌... 你有没有想过,你的安卓手机桌面操作系统,其实就像是一个小小的魔法世界呢?在这个世界里,你可以随意布置...