Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Download Speed

Tags:

java

stream

I am downloading a file but trying to also determine the download speed in KBps. I came up with an equation, but it is giving strange results.

    try (BufferedInputStream in = new BufferedInputStream(url.openStream());
        FileOutputStream out = new FileOutputStream(file)) {
        byte[] buffer = new byte[4096];
        int read = 0;
        while (true) {
            long start = System.nanoTime();
            if ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            } else {
                break;
            }
            int speed = (int) ((read * 1000000000.0) / ((System.nanoTime() - start) * 1024.0));
        }
    }

It's giving me anywhere between 100 and 300,000. How can I make this give the correct download speed? Thanks

like image 878
Stripies Avatar asked Nov 04 '22 18:11

Stripies


1 Answers

You are not checking your currentAmmount and previousAmount of file downloading.

example

int currentAmount = 0;//set this during each loop of the download
/***/
int previousAmount = 0;
int firingTime = 1000;//in milliseconds, here fire every second
public synchronyzed void run(){
    int bytesPerSecond = (currentAmount-previousAmount)/(firingTime/1000);
    //update GUI using bytesPerSecond
    previousAmount = currentAmount;    
}
like image 118
Mohammod Hossain Avatar answered Nov 08 '22 16:11

Mohammod Hossain