我正在软件上下载一个文件,这就是我得到的,它成功地下载了,我也可以获得进度,但还有一件事我不知道该怎么做。测量下载速度。我将感谢你的帮助。谢谢这是当前的下载方法代码
public void run()
{
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try
{
URL url1 = new URL(url);
out = new BufferedOutputStream(
new FileOutputStream(sysDir+"\"+where));
conn = url1.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
double progress1;
while ((numRead = in.read(buffer)) != -1)
{
out.write(buffer, 0, numRead);
numWritten += numRead;
this.speed= (int) (((double)
buffer.length)/8);
progress1 = (double) numWritten;
this.progress=(int) progress1;
}
}
catch (Exception ex)
{
echo("Unknown Error: " + ex);
}
finally
{
try
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
catch (IOException ex)
{
echo("Unknown Error: " + ex);
}
}
}
测量任何东西的方法都是一样的。
System.nanoTime()
返回一个Long
,您可以使用它来测量某件事需要多长时间:
Long start = System.nanoTime();
// do your read
Long end = System.nanoTime();
现在您有了读取X字节所花费的纳秒数。计算一下,你就有了下载率。
你很可能在寻找每秒字节数。记录您读取的字节总数,检查是否已经过了一秒钟。一秒钟后,根据你在这段时间内读取的字节数计算出速率。重置总数,重复。
这是我的实现
while (mStatus == DownloadStatus.DOWNLOADING) {
/*
* Size buffer according to how much of the file is left to
* download.
*/
byte buffer[];
// handled resume case.
if ((mSize < mDownloaded ? mSize : mSize - mDownloaded <= 0 ? mSize : mSize - mDownloaded) > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (mSize - mDownloaded)];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;// EOF, break while loop
// Write buffer to file.
file.write(buffer, 0, read);
mDownloaded += read;
double speedInKBps = 0.0D;
try {
long timeInSecs = (System.currentTimeMillis() - startTime) / 1000; //converting millis to seconds as 1000m in 1 second
speedInKBps = (mDownloaded / timeInSecs) / 1024D;
} catch (ArithmeticException ae) {
}
this.mListener.publishProgress(this.getProgress(), this.getTotalSize(), speedInKBps);
}
我可以给你一个大致的想法。在下载开始时启动计时器。现在,将(percentage downloaded)
乘以download size
,再除以time elapsed.
,得到平均下载时间。希望我能让你走上正轨!
您可以按照Brian的建议使用System.nanoTime();
。
将long startTime = System.nanoTime();
置于while循环之外。和
long estimatedTime = System.nanoTime() - startTime;
将为您提供循环中经过的时间。