计算下载速度

Str*_*ies 5 java stream

我正在下载文件,但还尝试以KBps确定下载速度.我提出了一个等式,但它给出了奇怪的结果.

    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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

它给了我100到300,000之间的任何地方.如何才能使下载速度正确?谢谢

Moh*_*ain 2

您没有检查您的 currentAmmount 和 previousAmount 文件下载量。

例子

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;    
}
Run Code Online (Sandbox Code Playgroud)