There is a method for downloading a file via Http:
private static void downloadFile(String strURL, String strPath, int buffSize) { try { /* Get connection */ URL connection = new URL(strURL); HttpURLConnection urlconn; urlconn = (HttpURLConnection) connection.openConnection(); urlconn.setRequestMethod("GET"); urlconn.connect(); /* Set input stream */ InputStream in = null; in = urlconn.getInputStream(); /* Set write stream */ OutputStream writer = new FileOutputStream(strPath); byte buffer[] = new byte[buffSize]; // Max bytes per one reception /* Download */ int i = 0; while ((i = in.read(buffer)) > 0) { writer.write(buffer, 0, i); } /* Cleaning */ writer.flush(); writer.close(); in.close(); } catch (IOException e) { System.out.println(e); } } I like the simple output like: System.out.println("Speed: " + Mb + "/sec");
I wanted to use the Timer and TimerTask . But, their methods schedule() , scheduleAtFixedRate() not suitable, since they are executed only after Thread.sleep(x); but I don't know how long ( x ) the download will take.
I can output the number of bytes i received in one iteration of the loop (~ 1ms), but I want it in 1s. It is possible, of course, to add a variable number of ms to int , to another number of bytes, and when there will be> 1000 ms output speed, but surely there is a better way?
System.currentTimeMillis()before the loop. Then at the end of the iteration we call the method again and see the difference. Equal to or greater than a second - send the speed value to the method of calculating the value for the moving average. - DimXenon