package unit;

 import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 文件下载
*/
public class HttpUtils {
static long sumContent = 0;
static float useTime = 0;
ArrayList<Float> speed = new ArrayList<Float>();
public static void main(String[] args) {
String url ="http://xcy1.xiaoshikd.com/python3.zip\r\n";
String dirPath = "D:/111/downLoad/";
String dirPath2 = "D:/222/downLoad/";
String dirPath3 = "D:/333/downLoad/";
HttpUtils.download(url, dirPath, "============");
HttpUtils.download(url, dirPath2, "============================");
HttpUtils.download(url, dirPath3, "==============================================");
} public static void download(String url, String filePath, final String message) {
HttpUtils.getInstance().download(url, filePath, new HttpClientDownLoadProgress() {
@Override
public void onProgress(int progress) {
System.out.println("download progress "+message+ progress+"%");
}
});
} /**
* 最大线程池
*/
public static final int THREAD_POOL_SIZE = 4; public interface HttpClientDownLoadProgress {
public void onProgress(int progress);
} private static HttpUtils httpClientDownload; private ExecutorService downloadExcutorService; private HttpUtils() {
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
} public static HttpUtils getInstance() {
if (httpClientDownload == null) {
httpClientDownload = new HttpUtils();
}
return httpClientDownload;
} /**
* 下载文件
*
* @param url
* @param filePath
* @param progress
* 进度回调
*/
public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) {
downloadExcutorService.execute(new Runnable() {
@Override
public void run() {
httpDownloadFile(url, filePath, progress);
}
});
} /**
* 下载文件
* @param url
* @param filePath
*/
private void httpDownloadFile(String strUrl, String filePath, HttpClientDownLoadProgress progress) {
try {
long startTime = System.currentTimeMillis();
URL url = new URL(strUrl);
String file = url.getFile();
String fileName = file.substring(file.lastIndexOf('/')+1);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long contentLength = conn.getContentLength();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[65536];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
sumContent+=r;
if (progress != null) {// 回调进度
progress.onProgress((int) (totalRead * 100 / contentLength));
}
} /**
* 将下载文件写入本地
*/
File f = new File(filePath);
if(!f.exists()) {
f.mkdirs();
}
filePath = filePath+fileName;
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush(); Long endTime = System.currentTimeMillis();
useTime = (float)(endTime-startTime)/1000;
getDoloadResult(sumContent, useTime); output.close();
fos.close();
is.close();
downloadExcutorService.shutdown();
} catch (Exception e) {
e.printStackTrace();
downloadExcutorService.shutdown();
}
} public void getDoloadResult(long contentLength, float useTime) {
System.out.println("sumContentLength: "+contentLength);
System.out.println("useTime: "+useTime); float bySpead = contentLength/useTime/1024/1024;
BigDecimal b = new BigDecimal(bySpead);
bySpead = b.setScale(2, 4).floatValue();;
speed.add(bySpead);
System.out.println("avgSpeed: "+bySpead+" M/s");
System.out.println("maxSpeed: "+Collections.max(speed)+" M/s");
}
}

Http多线程下载文件的更多相关文章

  1. Python之FTP多线程下载文件之分块多线程文件合并

    Python之FTP多线程下载文件之分块多线程文件合并 欢迎大家阅读Python之FTP多线程下载系列之二:Python之FTP多线程下载文件之分块多线程文件合并,本系列的第一篇:Python之FTP ...

  2. Python之FTP多线程下载文件之多线程分块下载文件

    Python之FTP多线程下载文件之多线程分块下载文件 Python中的ftplib模块用于对FTP的相关操作,常见的如下载,上传等.使用python从FTP下载较大的文件时,往往比较耗时,如何提高从 ...

  3. 多线程下载文件,ftp文件服务器

    1: 多线程下载文件 package com.li.multiplyThread; import org.apache.commons.lang3.exception.ExceptionUtils; ...

  4. 教你如何在 Android 使用多线程下载文件

    # 教你如何在 Android 使用多线程下载文件 前言 在 Android 日常开发中,我们会经常遇到下载文件需求,这里我们也可以用系统自带的 api DownloadManager 来解决这个问题 ...

  5. java 多线程下载文件 以及URLConnection和HttpURLConnection的区别

    使用 HttpURLConnection 实现多线程下载文件 注意GET大写//http public class MultiThreadDownload { public static void m ...

  6. java 多线程下载文件并实时计算下载百分比(断点续传)

    多线程下载文件 多线程同时下载文件即:在同一时间内通过多个线程对同一个请求地址发起多个请求,将需要下载的数据分割成多个部分,同时下载,每个线程只负责下载其中的一部分,最后将每一个线程下载的部分组装起来 ...

  7. java 网络编程基础 InetAddress类;URLDecoder和URLEncoder;URL和URLConnection;多线程下载文件示例

    什么是IPV4,什么是IPV6: IPv4使用32个二进制位在网络上创建单个唯一地址.IPv4地址由四个数字表示,用点分隔.每个数字都是十进制(以10为基底)表示的八位二进制(以2为基底)数字,例如: ...

  8. AccessRandomFile多线程下载文件

    写一个工具类 package com.pb.thread.demo; import java.io.File; import java.io.FileNotFoundException; import ...

  9. WPF多线程下载文件,有进度条

    //打开对话框选择文件         private void OpenDialogBox_Click(object sender, RoutedEventArgs e)         {     ...

  10. python多线程下载文件

    从文件中读取图片url和名称,将url中的文件下载下来.文件中每一行包含一个url和文件名,用制表符隔开. 1.使用requests请求url并下载文件 def download(img_url, i ...

随机推荐

  1. Part4_lesson4---Bootloader架构设计

    1.第一阶段程序设计 第二阶段程序设计

  2. 解决linux下80端口占用问题

    在即安装有tomcat,又安装有nginx的服务器上(典型阿里云驻云java镜像),系统默认配置nginx占用80端口,tomcat占用8080端口. 如果想要便于用户可以直接通过IP或者域名访问到t ...

  3. 策略与计费控制(PCC)流程与信令流程

    该文为3GPP TS23.203-be0 条款6-7译文 策略与计费控制(PCC)流程[^4] IP-CAN 会话有三种显著的场景: 无网关控制会话需求,不会出现网关控制建立 需要网关控制会话支持:B ...

  4. CentOS 用户/组与权限

    useradd:添加用户 useradd abc,默认添加一个abc组 vipw:查看系统中用户 groupadd:添加组groupadd ccna vigr:查看系统中的组 gpasswd:将用户a ...

  5. windows下go调用内存dll

    有时候我们希望将dll嵌入到程序内部,以提高程序的安全性,这里我写的一个开源memorydll模块. 首先 go get github.com/nkbai/go-memorydll 然后在需要的时候 ...

  6. 基于verilog的FFT算法8点12位硬件实现

    FFT算法8点12位硬件实现 (verilog) 1 一.功能描述: 1 二.设计结构: 2 三.设计模块介绍 3 1.蝶形运算(第一级) 3 2.矢量角度旋转(W) 4 3.CORDIC 结果处理 ...

  7. 6步完成压力测试工具Locust部署和使用

    1,准备安装python,安装过程略 已安装的,查看安装目录: cmd输入where Python 2,pip安装locust 1.进入python所在目录,如果没有配置环境变量,需要进入到C:\Us ...

  8. c++基类指针指向继承类调用继承类函数

      类里面重载运算符>>, 需要使用友元函数,而友元函数,不能作为虚函数. 所以,基类指针无法直接调用继承类里重构的 >>  ; 使用类转换,能解决掉,基类指针 调用 继承类 ...

  9. linux centos 宝塔主机控制面板安装和安全狗安装过程记录

    linux 宝塔控制面板 安装过程yum install -y wget && wget -O install.sh http://103.224.251.79:5880/instal ...

  10. mysql设计-优化

    mysql表复制 1.复制表结构 create table student like user; 2.复制表内容 insert into t3 select * from t1; mysql索引 1. ...