有人知道如何使用网址(http://.../File.mp4)从互联网上下载文件吗?我正在尝试使用NIO,但总是以Integer.MAX_VALUE结束。我的文件是2.5GB。
我的代码:
String url = "http://.../Somefile.mp4";
String filename = "Path/to/file/Something.mp4";
boolean koncano = false;
URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("Range", "bytes=" + new File(filename).length() + "-");
ReadableByteChannel rbc = Channels.newChannel(conn.getInputStream());
long remain = conn.getContentLength();
FileOutputStream fos = new FileOutputStream(filename, true);
while (!koncano) {
long downloaded = new File(filename).length();
long buffer = (remain > 65536) ? 1 << 16 : remain;
while (remain > 0) {
long write = fos.getChannel().transferFrom(rbc, downloaded, buffer);
downloaded += write;
remain -= write;
if (write == 0) {
break;
}
}
if (remain <= 0) {
System.out.println("File is complete");
rbc.close();
fos.close();
koncano = true;
}
}
答案 0 :(得分:1)
使用长版:
long remain = connection.getContentLengthLong();
提示:如果文件可以压缩到一小部分,您可以发送相应的Accept标头,并可选择将流包装在GZipInputStream中。
答案 1 :(得分:0)
尝试修改if (remain < 0)
至if (remain <= 0)