title: How to Display Transfer Rate per Second While Still Downloading the File
body: <p>i need to come out with a function to show size transfer rate per second. </p>
  
  <p>I have to download a file from web with my java code and display the transfer rate per second while downloading the file.</p>
  
  <p><img src="https://i.stack.imgur.com/D9KVF.png" alt="enter image description here"></p>
  
  <p>please note the code below is not totally mine, it was taken from <a href="https://stackoverflow.com/questions/15039660/calculating-network-download-speed">here</a>
  The code below only can calculate transfer rate after the download has finished, but i currently have no idea how to make the code to display transfer rate every second, any conceptual idea or code suggestion?</p>
  
  <pre><code>public static void main(String argc[]) throws Exception {
  
  long totalDownload       = 0;                      // total bytes downloaded
  final int BUFFER_SIZE    = 1024;                   // size of the buffer
  
  byte[] data = new byte[BUFFER_SIZE];               // buffer
  BufferedInputStream in = new BufferedInputStream(
  
      new URL(
              "http://ipv4.download.thinkbroadband.com:8080/5MB.zip")
              .openStream());
  
   int dataRead        = 0;                          // data read in each try
   long startTime      = System.nanoTime();          // starting time of download
   while ((dataRead    = in.read(data, 0, 1024)) &gt; 0) {
      totalDownload  += dataRead;                    // adding data downloaded to total data
      System.out.println(totalDownload);
  }
  
  /* download rate in bytes per second */
  float bytesPerSec = totalDownload
      / ((System.nanoTime() - startTime) / 1000000000);
  System.out.println(bytesPerSec + " Bps");
  
  /* download rate in kilobytes per second */
  float kbPerSec = bytesPerSec / (1024);
  System.out.println(kbPerSec + " KBps ");
  
  /* download rate in megabytes per second */
  float mbPerSec = kbPerSec / (1024);
  System.out.println(mbPerSec + " MBps ");
  }
  </code></pre>