java - 计算下载速度

标签 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));
        }
    }

它给了我 100 到 300,000 之间的任何地方。我怎样才能让它给出正确的下载速度?谢谢

最佳答案

您没有检查您当前的下载量和之前的文件下载量。

例子

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;    
}

关于java - 计算下载速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11912338/

相关文章:

node.js - NodeJS 流超出堆

java - PMML文档解析

java - 如何让 Android 按钮阵列的 onClickListener 正常工作

java - hibernate 执行延迟

java - 将 1's and 0' 排列在一个数组中

stream - Streaming 在 Streaming SIMD Extensions (SSE) 中代表什么?

java - 在 JPanel 中实现图形

javascript - 不在stream.Readable中实现_read的缺点

.net - 在 MSMQ 中发送二进制消息

php - echo 是否等于 fputs(STDout)?