测量下载速度Java

我正在努力下载一个软件上的文件,这是我得到的,它的sucesfully下载,我也可以取得进展,但还有一件事,我不知道该怎么做.测量下载速度.我很感激你的帮助.谢谢.
这是当前的下载方法代码
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,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字节所需的纳秒数.算一算,你就有了下载速度.

你很可能每秒都在寻找字节数.跟踪您已读取的总字节数,检查是否已经过了一秒.一秒钟后,根据您在该时间内读取的字节数计算出速率.重置总数,重复.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...