前言:

程序下载文件时,有时会因为各种各样的原因下载中断,对于小文件来说影响不大,可以快速重新下载,但是下载大文件时,就会耗费很长时间,所以断点续传功能对于大文件很有必要。

文件下载的断点续传:

  1、先下载临时文件,用于记录已下载大小:

    2、http请求时设置Range参数

      3、下载此次请求的数据;

直接上代码:

 package com.test.service;

 import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; /**
* <p>
* 文件下载,可以支持断点续传
* 暂未使用
* </p>
* @author
* @version 1.0
* */
@Component
public class DownloadOnly { private static final Logger logger = LoggerFactory.getLogger(DownloadOnly.class); @Value("${onair.download.ddxc:true}")
boolean ddxc = true; int startIndex = 0; long downloadSize = 0; boolean downloadFinish = false; int totleSize = 0; public boolean download(String url,String file_path,int downloadTimeout){ //起一个线程 检测下载进度
new Thread(new Runnable() { @Override
public void run() {
try {
NumberFormat nt = NumberFormat.getPercentInstance();
//设置百分数精确度3即保留三位小数
nt.setMinimumFractionDigits(1);
while(!downloadFinish){
Thread.sleep(30000);
logger.debug("已下载大小{},进度{}",getDownloadSize(),nt.format(getDownloadSize()* 1.0 /totleSize));
}
} catch (InterruptedException e) {
e.printStackTrace();
} }
}).start(); logger.info("下载文件:源路径{},目标路径:{}",url,file_path);
RandomAccessFile raf = null;
InputStream in = null; try {
URL file_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)file_url.openConnection();
conn.setConnectTimeout(downloadTimeout);
conn.setRequestMethod("GET");
File tmpFile = new File(file_path+"_tmp");
if(ddxc){
if(tmpFile.exists() && tmpFile.isFile()){
downloadSize = tmpFile.length();
startIndex = (int)downloadSize;
}
conn.setRequestProperty("Range", "bytes=" + startIndex + "-");
}else{
if(tmpFile.exists() && tmpFile.isFile())
tmpFile.delete();
}
int status = conn.getResponseCode();
totleSize = (int)downloadSize + conn.getContentLength();
logger.info("文件总大小{},下载请求获得的返回状态码:{},需要下载的大小{}",totleSize,status,totleSize-downloadSize);
if(status== 200 || status == 206 ){
raf = new RandomAccessFile(tmpFile, "rwd");
raf.seek(startIndex);
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int size = 0;
while((size=in.read(buffer)) !=-1 ){
raf.write(buffer, 0, size);
downloadSize += size;
}
raf.close();
in.close();
File dest = new File(file_path);
return tmpFile.renameTo(dest);
}
} catch (Throwable e) {
logger.error("文件下载失败:{}",e.getMessage(),e);
}finally {
downloadFinish = true; //下载完成或中断
}
return false;
} public long getDownloadSize() {
return downloadSize;
} public static void main(String[] args) {
DownloadOnly downloadOnly = new DownloadOnly();
} }

Java单线程文件下载,支持断点续传功能的更多相关文章

  1. 【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控

    参考上篇文章: <[SFTP]使用Jsch实现Sftp文件下载-支持断点续传和进程监控>:http://www.cnblogs.com/ssslinppp/p/6248763.html  ...

  2. php大文件下载支持断点续传

    <?php   /** php下载类,支持断点续传  *  *   Func:  *   download: 下载文件  *   setSpeed: 设置下载速度  *   getRange: ...

  3. Java多线程下载器FileDownloader(支持断点续传、代理等功能)

    前言 在我的任务清单中,很早就有了一个文件下载器,但一直忙着没空去写.最近刚好放假,便抽了些时间完成了下文中的这个下载器. 介绍 同样的,还是先上效果图吧. Jar包地址位于 FileDownload ...

  4. edtftpj让Java上传FTP文件支持断点续传

    在用Java实现FTP上传文件功能时,特别是上传大文件的时候,可以需要这样的功能:程序在上传的过程中意外终止了,文件传了一大半,想从断掉了地方继续传:或者想做类似迅雷下载类似的功能,文件太大,今天传一 ...

  5. php 支持断点续传的文件下载类

    php 支持断点续传的文件下载类 分类: php class2013-06-30 17:27 17748人阅读 评论(6) 收藏 举报 php断点续传下载http测试 php 支持断点续传,主要依靠H ...

  6. FTP文件上传 支持断点续传 并 打印下载进度(二) —— 单线程实现

    这个就看代码,哈哈哈哈哈  需要用到的jar包是: <dependency> <groupId>commons-net</groupId> <artifact ...

  7. java多线程分块上传并支持断点续传最新修正完整版本[转]

    package com.test; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.Fi ...

  8. 【Servlet】java web 文件下载功能实现

    需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一:通过超链接实现下载 在HTML网页中,通过超链接链接到要下载的文件的地址 <!DOCTYPE html> & ...

  9. Java实现的断点续传功能

    代码中已经加入了注释,需要的朋友可以直接参考代码中的注释.下面直接上功能实现的主要代码: import java.io.File; import java.io.FileNotFoundExcepti ...

随机推荐

  1. jQuery 提供多个与 AJAX 有关的方法。

    jQuery 提供多个与 AJAX 有关的方法. 通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本.HTML.XML 或 JSON - ...

  2. 去除MyEclipse频繁弹出的Update Progress窗口

    方法1: 1.关闭updating index Window => Preferences => Myeclipse Enterprise Workbench => Maven4My ...

  3. iframe访问子页面方法

    在Iframe中调用子页面的Js函数 调用IFRAME子页面的JS函数 说明:假设有2个页面,index.html和inner.html.其中index.html中有一个iframe,这个iframe ...

  4. 浅尝JavaScript document对象

    document对象 每个载入浏览器的 HTML 文档都会成为 Document 对象.document 对象是HTML文档的根节点与所有其他节点(元素节点,文本节点,属性节点, 注释节点).Docu ...

  5. java中得到图片的宽度 高度:

    java中得到图片的宽度 高度:BufferedImage srcImage = null;srcImage = ImageIO.read(new File(srcImagePath));int sr ...

  6. 深入浅出TCP/IP协议栈

    TCP/IP协议栈是一系列网络协议的总和,是构成网络通信的核心骨架,它定义了电子设备如何连入因特网,以及数据如何在它们之间进行传输.TCP/IP协议采用4层结构,分别是应用层.传输层.网络层和链路层, ...

  7. PHP中小小的header函数

    不废话,直接说功能 1.重定向,语法: header("location:http://www.lemon-x.ga"); file_put_contents("./te ...

  8. Python的迭代器与生成器

    Python中的生成器和迭代器方便好用,但是平时对生成器和迭代器的特性掌握的不是很到位,今天将这方面的知识整理一下. 迭代器 为了更好的理解迭代器和生成,我们需要简单的回顾一下迭代器协议的概念. 迭代 ...

  9. [ABP框架]动态web Api的拦截用法。

    先进行配置 首先这种需求,一般发生在APP端,我们给APP,不会给所有项目系统的接口给他们用.我们系统有200个接口,但是APP的需求只会用20个.那么这个需求也就应运而生了. 以上为API文件夹中为 ...

  10. Mathematica 10 Mac 设置默认工作目录

    用SetDirectory命令设置