我正在下载一个文件,但也试图确定以 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/