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. ssh -X前设置DISPLAY=localhost:0

    如果是在windows上用XMing做XServer,前面的localhost不能省,否则会被当作一个unix domain socket,而XMing没有实现这个功能,所以会出错 connect / ...

  2. Action Results in MVC

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

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

  4. 命令之 ulimit

    help ulimit help ulimit ulimit: ulimit [-SHacdefilmnpqrstuvx] [limit] Modify shell resource limits. ...

  5. Storm的wordCounter计数器详解

    原文:http://www.maoxiangyi.cn/index.php/archives/362 拓扑 点击(此处)折叠或打开 package cn.jd.storm; import backty ...

  6. (转)Asp.Net底层原理(三、Asp.Net请求响应过程)

    原文地址:http://www.cnblogs.com/liuhf939/archive/2013/09/16/3324753.html 在之前,我们写了自己的Asp.Net框架,对整个流程有了一个大 ...

  7. 关于AJAX与JSON的杂记

    一.当网页需要有多个XMLHttpRequest对象时,可以使用Callback 函数,callback 函数是一种以参数形式传递给另一个函数的函数. <html> <head> ...

  8. 挂载ISO 和 KILL 掉占用进程

    mount -t iso9660 -o loop,user VMware-tools-linux-8.6.0-425873.iso /mnt/cdrom fuser -m -v -i -k  /mnt ...

  9. .net Stream篇(七)

    NetworkStream 目录: NetworkStream的作用 简单介绍下TCP/IP 协议和相关层次 简单说明下 TCP和UDP的区别 简单介绍下套接字(Socket)的概念 简单介绍下Tcp ...

  10. NSLocale 本地化信息

    前言 NSLocale 类返回本地化信息,主要体现在"语言"和"区域格式"这两个设置项. 1.NSLocale 本地化信息的创建 // 用标示符创建 NSLoc ...