Calculating Download Speed

Viewed 2799

I am downloading a file but trying to also determine the download speed in KBps. I came up with an equation, but it is giving strange results.

    try (BufferedInputStream in = new BufferedInputStream(url.openStream());
        FileOutputStream out = new FileOutputStream(file)) {
        byte[] buffer = new byte[4096];
        int read = 0;
        while (true) {
            long start = System.nanoTime();
            if ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            } else {
                break;
            }
            int speed = (int) ((read * 1000000000.0) / ((System.nanoTime() - start) * 1024.0));
        }
    }

It's giving me anywhere between 100 and 300,000. How can I make this give the correct download speed? Thanks

2 Answers
Related