用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 ...
随机推荐
- shit layui & bugs
shit layui & bugs use is not useful at all! http://www.layui.com/demo/form.html layui.use([" ...
- DIV垂直/水平居中2(DIV宽度和高度是动态的)
<!doctype html><html><head><meta charset="utf-8"><title>块元素D ...
- 暑假训练Round1——G: Hkhv的水题之二(字符串的最小表示)
Problem 1057: Hkhv的水题之二 Time Limits: 1000 MS Memory Limits: 65536 KB 64-bit interger IO format: ...
- 【2018.10.20】noip模拟赛Day3 飞行时间
今天模拟赛题目 纯考输入的傻逼题,用$scanf$用到思想僵化的我最终成功被$if$大法爆$0$了(这题只有一组$100$分数据). 输入后面那个$(+1/2)$很难$if$判断,所以我们要判两个字符 ...
- hdu 1717
小数化分数2 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Sub ...
- Codeforces Round #275 (Div. 2) B. Friends and Presents 二分+数学
8493833 2014-10-31 08:41:26 njczy2010 B - Friends and Presents G ...
- 前端开发之html篇
一.什么是html? 1.我们说socket网络编程的时候,提到过一个cs模型,就是客户端—服务端模型,前端开发也是基于网络编程,但是这时就应该是bs模型了,是浏览器与服务端的通信. 我们可以模拟一个 ...
- 计算机windows7连接打印机
计算机连接打印机 (1)查看打印机的名字. 示例,打印机名为 HP LaserJet M1522 .... (2)打开windows开始菜单,点击[设备和打印机],然后查看打印机和传真那个区域是否有打 ...
- grequests----golang的requests库
github.com/levigross/grequests: A Go "clone" of the great and famous Requests library 特点: ...
- win10+Linux18.04双系统安装
给好多可爱的妹子重装了那么多次电脑,懒得码过程,因为我一般每次都要查一查...这次来个综合版吧,超简单,无脑操作. 首先说一下我的电脑Thinkpad + 500G 硬盘 (2014年买的老电脑) 首 ...