java http多线程下载文件_Http多线程下载文件

1 packageunit;2

3 importjava.io.ByteArrayOutputStream;4 importjava.io.File;5 importjava.io.FileOutputStream;6 importjava.io.InputStream;7 importjava.math.BigDecimal;8 importjava.net.URL;9 importjava.net.URLConnection;10 importjava.util.ArrayList;11 importjava.util.Collections;12 importjava.util.concurrent.ExecutorService;13 importjava.util.concurrent.Executors;14

15 /**

16 * 文件下载17 */

18 public classHttpUtils {19 static long sumContent = 0;20 static float useTime = 0;21 ArrayList speed = new ArrayList();22 public static voidmain(String[] args) {23 String url ="http://xcy1.xiaoshikd.com/python3.zip\r\n";24 String dirPath = "D:/111/downLoad/";25 String dirPath2 = "D:/222/downLoad/";26 String dirPath3 = "D:/333/downLoad/";27 HttpUtils.download(url, dirPath, "============");28 HttpUtils.download(url, dirPath2, "============================");29 HttpUtils.download(url, dirPath3, "==============================================");30 }31

32 public static void download(String url, String filePath, finalString message) {33 HttpUtils.getInstance().download(url, filePath, newHttpClientDownLoadProgress() {34 @Override35 public void onProgress(intprogress) {36 System.out.println("download progress "+message+ progress+"%");37 }38 });39 }40

41 /**

42 * 最大线程池43 */

44 public static final int THREAD_POOL_SIZE = 4;45

46 public interfaceHttpClientDownLoadProgress {47 public void onProgress(intprogress);48 }49

50 private staticHttpUtils httpClientDownload;51

52 privateExecutorService downloadExcutorService;53

54 privateHttpUtils() {55 downloadExcutorService =Executors.newFixedThreadPool(THREAD_POOL_SIZE);56 }57

58 public staticHttpUtils getInstance() {59 if (httpClientDownload == null) {60 httpClientDownload = newHttpUtils();61 }62 returnhttpClientDownload;63 }64

65 /**

66 * 下载文件67 *68 *@paramurl69 *@paramfilePath70 *@paramprogress71 * 进度回调72 */

73 public void download(final String url, final String filePath, finalHttpClientDownLoadProgress progress) {74 downloadExcutorService.execute(newRunnable() {75 @Override76 public voidrun() {77 httpDownloadFile(url, filePath, progress);78 }79 });80 }81

82 /**

83 * 下载文件84 *@paramurl85 *@paramfilePath86 */

87 private voidhttpDownloadFile(String strUrl, String filePath, HttpClientDownLoadProgress progress) {88 try{89 long startTime =System.currentTimeMillis();90 URL url = newURL(strUrl);91 String file =url.getFile();92 String fileName = file.substring(file.lastIndexOf('/')+1);93 URLConnection conn =url.openConnection();94 InputStream is =conn.getInputStream();95 long contentLength =conn.getContentLength();96 ByteArrayOutputStream output = newByteArrayOutputStream();97 byte[] buffer = new byte[65536];98 int r = 0;99 long totalRead = 0;100 while ((r = is.read(buffer)) > 0) {101 output.write(buffer, 0, r);102 totalRead +=r;103 sumContent+=r;104 if (progress != null) {//回调进度

105 progress.onProgress((int) (totalRead * 100 /contentLength));106 }107 }108

109 /**

110 * 将下载文件写入本地111 */

112 File f = newFile(filePath);113 if(!f.exists()) {114 f.mkdirs();115 }116 filePath = filePath+fileName;117 FileOutputStream fos = newFileOutputStream(filePath);118 output.writeTo(fos);119 output.flush();120

121 Long endTime =System.currentTimeMillis();122 useTime = (float)(endTime-startTime)/1000;123 getDoloadResult(sumContent, useTime);124

125 output.close();126 fos.close();127 is.close();128 downloadExcutorService.shutdown();129 } catch(Exception e) {130 e.printStackTrace();131 downloadExcutorService.shutdown();132 }133 }134

135 public void getDoloadResult(long contentLength, floatuseTime) {136 System.out.println("sumContentLength: "+contentLength);137 System.out.println("useTime: "+useTime);138

139 float bySpead = contentLength/useTime/1024/1024;140 BigDecimal b = newBigDecimal(bySpead);141 bySpead = b.setScale(2, 4).floatValue();;142 speed.add(bySpead);143 System.out.println("avgSpeed: "+bySpead+" M/s");144 System.out.println("maxSpeed: "+Collections.max(speed)+" M/s");145 }146 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值