Java downloading a file and retrieving current download completion

977 views Asked by At

In a program I have that auto-updates, I need it to download a specific file (working already) and it does so with the following code:

public static void getFile() {
    try {
        URL url = new URL("https://dl.dropboxusercontent.com/s/tc301v61zt0v5cd/texture_pack.png?dl=1");
        InputStream in = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream(file4);
        fos.write(response);
        fos.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Check your internet connection, then try again.\nOr re-install the program.\nError Message 7", "Could Not Download The Required Resources.", JOptionPane.NO_OPTION);
        e.printStackTrace();
        System.exit(0);
    }
}

How would I implement a way to get the current completion of the download (like the percent it's downloaded) and put it into an integer to be printed out in the console (just for developer testing). Also what sort of equation could i use to get the estimated amount of time left on the download? Anything would help! Thanks.

2

There are 2 answers

1
Paul Hicks On

There is no way to get the size of a streamed file without streaming to the end of the file, so it can't be done within that block of code.

If you are willing to adopt the Dropbox API, you can use that to get the size of the file before starting the download. Then you can work with that size and the number bytes downloaded (n in your code) to achieve what you need.

The class in the Dropbox API that you need is DbxEntry.File.

2
maksimov On

If you examine the HTTP headers sent in the file download, you'll discover the file size. From this you can calculate percentage complete:

curl --head "https://dl.dropboxusercontent.com/s/tc301v61zt0v5cd/texture_pack.png?dl=1"

Gives you this:

HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="texture_pack.png"
Content-length: 29187
Content-Type: image/png
Date: Mon, 28 Apr 2014 22:38:34 GMT
etag: 121936d
pragma: public
Server: nginx
x-dropbox-request-id: 1948ddaaa2df2bdf2c4a2ce3fdbeb349
X-RequestId: 4d9ce90907637e06728713be03e6815d
x-server-response-time: 514
Connection: keep-alive

You may have to use something more advanced than standard Java library classes for your download to access the headers however, something like Apache HttpClient.