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. git 的使用方法

    git 的使用有3个主要步骤: 1.1 工作区域操作: 在自己的git账号下构建一个工作目录, 并往工作目录里添加文件内容(cp /root/data/VIP_Amount_prediction/* ...

  2. vue.js的一些模板指令简述

    1.模板指令都是写在<template></template>html里面   v-text : value是什么就显示什么,如果value里面有html的标签,也会直接显示出 ...

  3. laravel中的attach and detach toggle method

    创建模型 post  and  user 以及 users , posts ,user_post(favorities)测试数据 在此可以看上一篇中的数据,本次测试数据利用的上一篇的数据.detach ...

  4. 深数据 - Deep Data

    暂无中文方面的信息,E文的也非常少,原文连接: A lot of great pieces have been written about the relatively recent surge in ...

  5. 快速入手Web幻灯片制作

    在线幻灯片 使用markdown可以快速的写出优美的文档,接下来我介绍一些简单的语法,快速的用浏览器制作幻灯片. 最基本使用格式 <!DOCTYPE html> <html> ...

  6. Windows下配置Visualsvn Server时需要注意的几点事项

    1配置用户组与用户 用户组的权限高于用户的权限, 如果一个用户只有只读权限,同时被加入了拥有写权限的用户组中,此用户可以执行写操作. 2在Pre-commit hook下增加 强制添加注释的钩子脚本 ...

  7. android IntentService和ResultReceiver的异步处理

    IntentService和ResultReceiver的异步处理 1.在下载手机上从网络下载东西的时候会用到AsyncTask来方便处理,这里可以在用IntentService和ResultRece ...

  8. string Format转义大括号

    String.Format("{0} world!","hello") //将输出 hello world!,没有问题,但是只要在第一个参数的任意位置加上一个大 ...

  9. EIP权限工作流平台-升级说明(2018-12-04)

    表单生成器,文本框新增验证(默认验证及正则表达式) 列表查询支持复杂查询,支持文本框,下拉框,时间查询

  10. day02.1-字符串内置方法

    字符串——str的定义:test = "zizaijiapu" 特点:1. 字符串是可迭代对象: 2. 字符串中各元素是有序的: 3. 字符串一经创建,其内容值不可修改. 1. 查 ...