Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

java - How to Display Transfer Rate per Second While Still Downloading the File

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

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

enter image description here

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 ");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thilo

"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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...