我正在下载一个文件,但也试图确定以 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之间的任何地方。我怎样才能让它给出正确的下载速度?谢谢