【问题标题】:Java HTTPConnection retrieve file size before downloadingJava HTTPConnection 在下载前检索文件大小
【发布时间】:2013-09-26 19:47:14
【问题描述】:

我正在尝试使用以下代码从 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")

【问题讨论】:

    标签: java header download filesize httpconnection


    【解决方案1】:

    如果服务器没有指定Content-Length标头,获取内容长度的唯一方法就是下载整个文件,看看有多大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2013-06-23
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      相关资源
      最近更新 更多