Java HTTPConnection在下载之前检索文件大小

时间:2013-09-26 19:47:14

标签: java header download filesize httpconnection

我正在尝试使用以下代码从Web服务下载大型(11MB)JSON文件:

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();
}

然而,对con.getContentLength()的调用会阻塞该线程几分钟,同时它会下载我认为的整个文件。

问题是我需要在下载开始之前快速发现文件大小,以便我可以相应地通知用户。

注意:已尝试致电con.connect()con.getHeaderField("Content-Length")

1 个答案:

答案 0 :(得分:1)

如果服务器未指定Content-Length标头,获取内容长度的唯一方法是下载整个文件并查看其大小。

相关问题