用Java编写的http下载工具类,包含下载进度回调
HttpDownloader.java
package com.buyishi; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; public class HttpDownloader { private final String url, destFilename; public HttpDownloader(String url, String destFilename) {
this.url = url;
this.destFilename = destFilename;
} public void download(Callback callback) {
try (FileOutputStream fos = new FileOutputStream(destFilename)) {
URLConnection connection = new URL(url).openConnection();
long fileSize = connection.getContentLengthLong();
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[10 * 1024 * 1024];
int numberOfBytesRead;
long totalNumberOfBytesRead = 0;
while ((numberOfBytesRead = inputStream.read(buffer)) != - 1) {
fos.write(buffer, 0, numberOfBytesRead);
totalNumberOfBytesRead += numberOfBytesRead;
callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
}
callback.onFinish();
} catch (IOException ex) {
callback.onError(ex);
}
} public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex);
}
}
OkHttpDownloader.java //基于OkHttp
package com.buyishi; import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody; public class OkHttpDownloader { private final String url, destFilename;
private static final Logger LOGGER = Logger.getLogger(OkHttpDownloader.class.getName()); public OkHttpDownloader(String url, String destFilename) {
this.url = url;
this.destFilename = destFilename; } public void download(Callback callback) {
BufferedInputStream input = null;
try (FileOutputStream fos = new FileOutputStream(destFilename)) {
Request request = new Request.Builder().url(url).build();
ResponseBody responseBody = new OkHttpClient().newCall(request).execute().body();
long fileSize = responseBody.contentLength();
input = new BufferedInputStream(responseBody.byteStream());
byte[] buffer = new byte[10 * 1024 * 1024];
int numberOfBytesRead;
long totalNumberOfBytesRead = 0;
while ((numberOfBytesRead = input.read(buffer)) != - 1) {
fos.write(buffer, 0, numberOfBytesRead);
totalNumberOfBytesRead += numberOfBytesRead;
callback.onProgress(totalNumberOfBytesRead * 100 / fileSize);
}
callback.onFinish();
} catch (IOException ex) {
callback.onError(ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
} public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex);
}
}
MainFrame.java //对两个工具类的测试
package com.buyishi; import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame; public class MainFrame extends JFrame { private final JButton test1Button, test2Button;
private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName()); private MainFrame() {
super("Download Test");
super.setSize(300, 200);
super.setLocationRelativeTo(null);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setLayout(new GridLayout(2, 1));
test1Button = new JButton("测试1");
test2Button = new JButton("测试2");
super.add(test1Button);
super.add(test2Button);
test1Button.addMouseListener(new MouseAdapter() {
private boolean downloadStarted; @Override
public void mouseClicked(MouseEvent e) {
if (!downloadStarted) {
downloadStarted = true;
new Thread() {
@Override
public void run() {
String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
// String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
new HttpDownloader(url, "C:/Users/BuYishi/Desktop/file1").download(new HttpDownloader.Callback() {
@Override
public void onProgress(long progress) {
LOGGER.log(Level.INFO, "{0}", progress);
test1Button.setText("Downloading..." + progress + "%");
} @Override
public void onFinish() {
LOGGER.log(Level.INFO, "Download finished");
test1Button.setText("Downloaded");
} @Override
public void onError(IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
downloadStarted = false;
}
});
}
}.start();
}
}
});
test2Button.addMouseListener(new MouseAdapter() {
private boolean downloadStarted; @Override
public void mouseClicked(MouseEvent e) {
if (!downloadStarted) {
downloadStarted = true;
new Thread() {
@Override
public void run() {
String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE";
// String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe";
new OkHttpDownloader(url, "C:/Users/BuYishi/Desktop/file2").download(new OkHttpDownloader.Callback() {
@Override
public void onProgress(long progress) {
test2Button.setText("Downloading..." + progress + "%");
} @Override
public void onFinish() {
test2Button.setText("Downloaded");
} @Override
public void onError(IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
downloadStarted = false;
}
});
}
}.start();
}
}
});
} public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
}
用Java编写的http下载工具类,包含下载进度回调的更多相关文章
- ftp上传下载工具类
package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- Java汉字转成汉语拼音工具类
Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...
- java中excel导入\导出工具类
1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
- java代码行数统计工具类
package com.syl.demo.test; import java.io.*; /** * java代码行数统计工具类 * Created by 孙义朗 on 2017/11/17 0017 ...
- Java加载Properties配置文件工具类
Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...
- Java 操作Redis封装RedisTemplate工具类
package com.example.redisdistlock.util; import org.springframework.beans.factory.annotation.Autowire ...
- java后台表单验证工具类
/** * 描述 java后台表单验证工具类 * * @ClassName ValidationUtil * @Author wzf * @DATE 2018/10/27 15:21 * @VerSi ...
随机推荐
- hdu6058[链表维护] 2017多校3
用一个双向链表来查找比当前元素大的前k-1个元素和后k-1个元素 ,从小到大枚举x,算完x的贡献后将x从链表中删除,优化到O(nk). /*hdu6058[链表维护] 2017多效3*/ #inclu ...
- P3147 [USACO16OPEN]262144 (贪心)
题目描述 给定一个1*n的地图,在里面玩2048,每次可以合并相邻两个(数值范围1-262,144),问最大能合出多少.注意合并后的数值并非加倍而是+1,例如2与2合并后的数值为3. 这道题的思路: ...
- chef cookbook 实战
在Workstation中创建cookbook,并且上传到Chef server,以及其他与Chef相关的工作. 安装chef client命令 knife bootstrap 10.6.1.207 ...
- 洛谷 P 1330 封锁阳光大学
题目描述 曹是一只爱刷街的老曹,暑假期间,他每天都欢快地在阳光大学的校园里刷街.河蟹看到欢快的曹,感到不爽.河蟹决定封锁阳光大学,不让曹刷街. 阳光大学的校园是一张由N个点构成的无向图,N个点之间由M ...
- 让Mac OS X下的终端像Linux那样拥有丰富多彩的颜色显示
我们知道Linux下的命令行终端具有颜色回显功能,用ls命令查看目录或者文件,终端会以不同的颜色来区分:使用vim命令行编辑器打开脚本或其他源程序代码会以语法高亮模式显示.而Mac OS X下的终端却 ...
- Mac OS X 10.10.5 中 VirtualBox 5.0 里的 Win7 虚拟机无法使用 USB 3.0 设备的解决办法(补充说明)
上一篇文章中,我说到了如何在Mac OS X 10.10.5 中让 VirtualBox 5.0 里的 Win7 虚拟机使用 USB 3.0.最近碰巧升级 MacBook Pro 为最新的 15 吋 ...
- electron 编译成exe
前提:现在有一个electron项目,等待打包成exe. 一,运行”electron .“,看运行是否正常.不正常则继续调试,正常可进入到第二步. 二,运行“electron-packager . m ...
- vue搭建cli脚手架环境(出现问题及解决,主要是node版本低)
Vue 提供了一个官方的cli,为单页面应用 (SPA) 快速搭建繁杂的脚手架. 一.vue cli脚手架 脚手架通过webpack搭建开发环境 使用ES6语法 打包压缩js为一个文件 项目文件在环境 ...
- MySql常用函数积累
--MySql查看表结构 select column_name,data_type,CHARACTER_MAXIMUM_LENGTH,column_comment from information_s ...
- lib无法访问另外lib中的头文件
工程中app已经有设置User Header Search Paths来包含了需要的头文件,但是个别的lib依然找不到头文件.解决方法: 选择这个lib,在Build Settings中查找选项Use ...