测量下载速度 Java [英] Measuring Download Speed Java

查看:20
本文介绍了测量下载速度 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在下载一个软件上的文件,这就是我得到的,它成功下载,而且我可以取得进展,但还有一件事我不知道该怎么做.测量下载速度.我会很感激你的帮助.谢谢.这是当前的下载方法代码

I'm working on downloading a file on a software, this is what i got, it sucesfully download, and also i can get progress, but still 1 thing left that I dont know how to do. Measure download speed. I would appreciate your help. Thanks. This is the current download method code

    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);
            }
        }
    }

推荐答案

与衡量任何事物的方式相同.

The same way you would measure anything.

System.nanoTime() 返回一个 Long,你可以用它来衡量某件事需要多长时间:

System.nanoTime() returns a Long you can use to measure how long something takes:

Long start = System.nanoTime();
// do your read
Long end = System.nanoTime();

现在您获得了读取 X 字节所需的纳秒数.算一算,你就有了下载率.

Now you have the number of nanoseconds it took to read X bytes. Do the math and you have your download rate.

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

More than likely you're looking for bytes per second. Keep track of the total number of bytes you've read, checking to see if one second has elapsed. Once one second has gone by figure out the rate based on how many bytes you've read in that amount of time. Reset the total, repeat.

这篇关于测量下载速度 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆