测量下载速度Java
我正在努力下载一个软件上的文件,这是我得到的,它可以下载,并且我可以获得进步,但还有一件事我不知道该怎么做。 测量下载速度。 我很感激你的帮助。 谢谢。 这是当前的下载方法代码
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字节所需的纳秒数。 算一算,你有下载速度。
你很可能每秒都在寻找字节数。 跟踪您已读取的总字节数,检查是否已经过了一秒。 一秒钟后,根据您在该时间内读取的字节数计算出速率。 重置总数,重复。
我可以给你一个大致的想法。 在下载开始时启动计时器。 现在,将(percentage downloaded)
的(percentage downloaded)
乘以download size
,并将其除以time elapsed.
这给你平均下载时间。 希望我能让你走上正轨!
你可以使用System.nanoTime();
正如Brian所说。
put long startTime = System.nanoTime();
在你的while循环之外。 和
long estimatedTime = System.nanoTime() - startTime;
会给你循环中经过的时间。
这是我的实施
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); }
- Java – 告诉String是否被实习?
- 如何使用“构造函数”在“选择子句”中为多个表的选定列编写HQL JOIN查询
- 重用PreparedStatement时可能出现资源泄漏?
- 如何在oibernate中将oracle timestamp映射到适当的java类型?
- 如何为浏览器applet指定特定的JRE?
- 使用Java中特殊字符之前的转义替换特殊字符
- Spring 4 MVC和Websockets – 没有合适的默认RequestUpgradeStrategy
- 如何在Hibernate Interceptor中获取Hibernate会话?
- 为什么在JFrame上设置setPreferredSize()很糟糕?