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. PHP数组的详细解读

    数组的定义 数组的本质是管理和操作一组变量,数组中可以存储任意长度的数据,也可以存储任意类型的数据.数组中的单元称为元素,每个元素包括下标(键)和值,访问元素的时候,是通过下标来访问,包括一维数组,二 ...

  2. seconds

    set_time_limit();//设置脚本运行时间为1秒

  3. linux信号基本概念及如何产生信号

    linux信号基本概念及如何产生信号 摘自:https://blog.csdn.net/summy_j/article/details/73199069 2017年06月14日 09:34:21 阅读 ...

  4. python核心编程第5章课后题答案

    5-8Geometry import math def sqcube(): s = float(raw_input('enter length of one side: ')) print 'the ...

  5. Quartus II 14.0正式版 下载链接和破解器

    Windows版本 必装组件: Quartus II http://download.altera.com/akdlm/software/acdsinst/14.0/200/ib_installers ...

  6. Struts2 配置及运行时遇到问题

    1.java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilt ...

  7. 状态压缩-----HDU1074 Doing Homework

    HDU1074 Doing Homework 题意:给了n个家庭作业,然后给了每个家庭作业的完成期限和花费的实践,如果完成时间超过了期限,那么就要扣除分数,然后让你找出一个最优方案使扣除的分数最少,当 ...

  8. JAVA自动装箱拆箱与常量池

    java 自动装箱与拆箱 这个是jdk1.5以后才引入的新的内容,作为秉承发表是最好的记忆,毅然决定还是用一篇博客来代替我的记忆: java语言规范中说道:在许多情况下包装与解包装是由编译器自行完成的 ...

  9. python 日志模块工具类

    #!/usr/bin/env python # -*- coding: utf-8 -*- import logging # logName 日志中的某个格式化的字段名,logFile生成的日志文件名 ...

  10. SharePoint 2013报错之“指定的文件不是有效的电子表格或者没有包含要导入的数据”

    当你尝试用SharePoint 2013中的“导入电子表格”功能时,可能会遇到报错“指定的文件不是有效的电子表格或者没有包含要导入的数据” 解决方法:只需要将你的SharePoint网址添加到浏览器的 ...