gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:22:54 26 4
gpt4 key购买 nike

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

最佳答案

如果服务器未指定Content-Length header ,则获取内容长度的唯一方法是下载整个文件并查看它有多大。

关于Java HTTPConnection 在下载之前检索文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19037337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com