有谁知道如何使用URL(http://.../File.mp4)从互联网下载文件?我正在尝试使用NIO,但总是以Integer.MAX_VALUE结束。我的文件是2.5GB。Java-如何从URL下载文件,大于Integer.MAX_VALUE
我的代码:
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;
}
}
欢迎来到Stack Overflow!寻求调试帮助的问题(“为什么这个代码不工作?”)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者无益。请参阅:如何创建[mcve]。使用“编辑”链接来改善你的*问题* - 不要通过评论添加更多信息。谢谢! – GhostCat
不要链接到外部网站 - 在你的问题中提供示例代码! – GhostCat
我怀疑你正在使用'HttpURLConnection'或者某物。类似的使用“ByteArrayInputStream”。这反过来使用'byte []',Java数组的最大长度为'Integer.MAX_VALUE'。 – Thomas