Saito Mea
Saito Mea

Reputation: 455

Java HTTPConnection retrieve file size before downloading

I am trying to download a large (11MB) JSON file from a web service using this code:

public static void downloadBigFile(final String serverUrl,
        final String fileName) throws MalformedURLException, IOException {
    System.out.println("Downloading " + serverUrl + " (" + fileName + ")");

    URL url = new URL(serverUrl);
    URLConnection con = url.openConnection();
    con.setConnectTimeout(10000);
    con.setReadTimeout(2 * 60 * 1000);

    int totalFileSize = con.getContentLength();
    System.out.println("Total file size: " + totalFileSize);

    InputStream inputStream = con.getInputStream();
    FileOutputStream outputStream = new FileOutputStream(fileName);

    // Used only for knowing the amount of bytes downloaded.
    int downloaded = 0;

    final byte[] buffer = new byte[1024 * 8];
    int bytesRead;

    bytesRead = inputStream.read(buffer);

    while (bytesRead != -1) {
        downloaded += bytesRead;
        outputStream.write(buffer, 0, bytesRead);
        bytesRead = inputStream.read(buffer);

        System.out.println(String.format("%d/%d (%.2f%%)", downloaded,
                totalFileSize,
                (downloaded * 1.0 / totalFileSize * 1.0) * 100));
    }

    System.out
            .println(fileName + " downloaded! (" + downloaded + " bytes)");

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

However the call to con.getContentLength() blocks the thread for several minutes, while it downloads the whole file I presume.

The problem is I need a quick way to discover file size before the download starts so I can notify the user accordingly.

Note: already tried to call con.connect() and con.getHeaderField("Content-Length").

Upvotes: 1

Views: 956

Answers (1)

Rob
Rob

Reputation: 6497

If the server does not specify the Content-Length header, the only way to get the content length is to download the whole file and see how big it is.

Upvotes: 1

Related Questions