如何在仍然下载文件的同时显示每秒传输速率 [英] How to Display Transfer Rate per Second While Still Downloading the File

查看:120
本文介绍了如何在仍然下载文件的同时显示每秒传输速率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提供一个显示每秒大小传输速率的功能。

i need to come out with a function to show size transfer rate per second.

我必须使用我的java代码从网上下载文件,并在下载文件时显示每秒的传输速率。

I have to download a file from web with my java code and display the transfer rate per second while downloading the file.

please请注意下面的代码不完全是我的,它来自这里
代码下面只能计算下载完成后的传输速率,但我目前不知道如何使代码每秒显示传输速率,任何概念或代码建议?

please note the code below is not totally mine, it was taken from here The code below only can calculate transfer rate after the download has finished, but i currently have no idea how to make the code to display transfer rate every second, any conceptual idea or code suggestion?

public static void main(String argc[]) throws Exception {

long totalDownload       = 0;                      // total bytes downloaded
final int BUFFER_SIZE    = 1024;                   // size of the buffer

byte[] data = new byte[BUFFER_SIZE];               // buffer
BufferedInputStream in = new BufferedInputStream(

    new URL(
            "http://ipv4.download.thinkbroadband.com:8080/5MB.zip")
            .openStream());

 int dataRead        = 0;                          // data read in each try
 long startTime      = System.nanoTime();          // starting time of download
 while ((dataRead    = in.read(data, 0, 1024)) > 0) {
    totalDownload  += dataRead;                    // adding data downloaded to total data
    System.out.println(totalDownload);
}

/* download rate in bytes per second */
float bytesPerSec = totalDownload
    / ((System.nanoTime() - startTime) / 1000000000);
System.out.println(bytesPerSec + " Bps");

/* download rate in kilobytes per second */
float kbPerSec = bytesPerSec / (1024);
System.out.println(kbPerSec + " KBps ");

/* download rate in megabytes per second */
float mbPerSec = kbPerSec / (1024);
System.out.println(mbPerSec + " MBps ");
}


推荐答案

Thilo

你有这个循环,一次下载1024个字节。你可以在同一个循环中更新一些统计数据(和它们的显示)。也许不是在每一次迭代中,而是每一次都是如此。除非下载完全挂起,这将为您提供定期更新。如果它挂起,您需要第二个线程来轮询统计信息

"You have this loop which downloads 1024 bytes at a time. You could in the same loop update some statistics (and their display). Maybe not in every single iteration, but every few. Unless the download totally hangs, this will give you regular updates. If it does hang, you'd need a second thread to poll the statistics"

这篇关于如何在仍然下载文件的同时显示每秒传输速率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆