title: Measuring download speed when using HttpURLConnection Java
body: <p>So I'm designing a download manager using java, I need to show the download speed to the user.<br>
  below is the code I've used to find the download speed in KB/s but I don't think it's measuring download speed correctly. it's measuring my download speed pretty inaccurately from 5 KB/s to 200000 KB/s which is weird, my real download speed is approximately 500 KB/s.<br>
  MAX_BUFFER_SIZE is 16384.  </p>
  
  <pre><code>   while (status == CURRENT) {
       /* Size buffer according to how much of the
          file is left to download. */
       byte buffer[];
       if (sizeOfFile - downloadedSize &gt; MAX_BUFFER_SIZE) {
           buffer = new byte[MAX_BUFFER_SIZE];
       } else {
           buffer = new byte[sizeOfFile - downloadedSize];
       }
  
       // Read from server into buffer and measuring download speed.
       Long t1 = System.nanoTime();
       int read = stream.read(buffer);
       Long t2 = System.nanoTime();
       downloadSpeed = ((double) read / (double)(t2 - t1)) * 1000000;
       System.out.println(downloadSpeed);
       if (read == -1)
           break;
  
       // Write buffer to file.
       file.write(buffer, 0, read);
       downloadedSize += read;
       publish(downloadedSize);
       while (status == PAUSED) {
           Thread.sleep(1);
       }
  
   }
  </code></pre>
  
  <p>I can't figure out what's wrong with my method.  </p>
  
  <p>Thanks in advance.</p>