Java HTTPConnection在下载之前检索文件大小
我试图使用以下代码从web服务下载一个大的(11MB)JSON文件:Java HTTPConnection在下载之前检索文件大小,java,header,download,filesize,httpconnection,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 + ")");
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(“内容长度”)
如果服务器未指定内容长度
标头,获取内容长度的唯一方法是下载整个文件并查看其大小。如果服务器未指定内容长度
头,获取内容长度的唯一方法是下载整个文件并查看其大小