How to get the progress and speed of download from Java?

0

I found a example to download an http file from java

public class DescargaHttp {

    private static final int BUFFER_SIZE = 4096;

    public static void descargarArchivo(String URLArchivo, String Directorio)
            throws IOException {
        URL url = new URL(URLArchivo);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");


            if (disposition != null) {

                int index = disposition.indexOf("NombreArchivo=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = URLArchivo.substring(URLArchivo.lastIndexOf("/") + 1,
                        URLArchivo.length());
            }

            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = Directorio + File.separator + fileName;

            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);



            }

            outputStream.close();
            inputStream.close();

            System.out.println("Archivo Descargado");
        } else {
            System.out.println("No se encuentra el archivo. Codigo Servidor HTTP: " + responseCode);
        }
        httpConn.disconnect();
    }
}

There is some way to get the speed and size downloaded (example 12.5 MB of 120 MB)

Try printing the

System.out.println(bytesRead);
System.out.println(inputStream);

However, I had never worked with the java downloads and I have no idea how I can obtain that data, I thought I would read the file size with Files.size(new File(filename).toPath()) but I do not know if it is the best.

    
asked by Angel Montes de Oca 24.01.2018 в 19:15
source

1 answer

1

You could try using the httpConn.getContentLengthLong() method to get the full size if it is available in the connection header.

For the speed I'm afraid you'd have to calculate it in each iteration of reading in the buffer based on the total bytes read and the total elapsed time.

    
answered by 24.01.2018 в 19:33