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. 235D Graph Game

    传送门 题目大意 https://www.luogu.org/problemnew/show/CF235D 分析 我们先考虑它是树的情况 我们设$event(x,y)$表示删除点x是y与x联通这件事对 ...

  2. jq获取table总行数

    var rows = $('table').find("tr").length;

  3. css总结11:css的overflow问题

    1 排版时经常遇到块级元素内容overflow,怎么妥当处理是一个关键. overflow的常用属性:  代码: <!DOCTYPE html><html lang="en ...

  4. 【leetcode】Move Zeroes

    Move Zeroes 题目: Given an array nums, write a function to move all 0‘s to the end of it while maintai ...

  5. [原创]Java源代码学习

    一.一些关键字 方法声明中的native:调用本地方法,该方法一般是用C或者C++写的 变量声明中的transient:在序列化过程中会忽略该变量,即不进行序列化保存 变量声明中的volatile:编 ...

  6. Windows系统版本判定那些事儿[转]

    Windows系统版本判定那些事儿 转自CSDN,原文链接,我比较不要脸, 全部给复制过来了 前言 本文并不是讨论Windows操作系统的版本来历和特点,也不是讨论为什么没有Win9,而是从程序员角度 ...

  7. SpringBoot+MyBatis+MySQL读写分离(实例)

    ​ 1. 引言 读写分离要做的事情就是对于一条SQL该选择哪个数据库去执行,至于谁来做选择数据库这件事儿,无非两个,要么中间件帮我们做,要么程序自己做.因此,一般来讲,读写分离有两种实现方式.第一种是 ...

  8. 解决JAR包里面打开源代码都是乱码

    下面是解决方案 通过eclipse浏览源代码时,发现中文注释为乱码的问题.其实这个eclipse默认编码造成的问题.可以通过以下方法解决: 修改Eclipse中文本文件的默认编码:windows-&g ...

  9. Java面向对象之多态(向上、向下转型) 入门实例

    一.基础概念 多态: 重点是对象的多态性.某一事物的多种体现形态. 多态的作用: 1.提高了代码的扩展性,后期出现的功能,可以被之前的程序所执行. 2.不能使用子类特有的功能.只能使用覆盖父类的功能. ...

  10. Python正则表达式匹配日期与时间

    #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Randy' import re from datetime import da ...