try{
InputStream is = new URL("http://www.domain.com/ubuntu-linux.iso").openStream();
byte[] buf = new byte[1024];
int n = 0;
startBytes = TrafficStats.getTotalRxBytes(); /*gets total bytes received so far*/
startTime = System.nanoTime();
while(n<200){
is.read(buf);
n++;
}
endTime = System.nanoTime();
endBytes = TrafficStats.getTotalRxBytes(); /*gets total bytes received so far*/
totalTime = endTime - startTime;
totalBytes = endBytes - startBytes;
}
catch(Exception e){
e.printStackTrace();
}
之后我只需要将传输的字节数除以所花费的时间,就可以得到以 bps 为单位的下载速度。问题: 1. 这个方法准确吗? 2. 你知道更好的方法吗?
非常感谢。
InputStream.read
不能保证完全填充缓冲区。你需要检查返回值以查看实际读取了多少字节。 - Jeffrey