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

查看:182
本文介绍了测量下载速度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);
            }
        }
    }


推荐答案

与测量任何东西一样。

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天全站免登陆