【问题标题】:Java- How to download file from URL, larger than Integer.MAX_VALUEJava-如何从 URL 下载文件,大于 Integer.MAX_VALUE
【发布时间】:2018-03-21 15:12:47
【问题描述】:

有人知道如何使用 URL (http://.../File.mp4) 从 Internet 下载文件吗?我正在尝试使用 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;
        }
    }

【问题讨论】:

  • 欢迎来到 Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建 minimal reproducible example。使用“编辑”链接改进您的问题 - 不要通过 cmets 添加更多信息。谢谢!
  • 不要链接到外部站点 - 在您的问题中提供示例代码!
  • 我怀疑您使用的是HttpURLConnection 或某事。类似的使用ByteArrayInputStream。这反过来使用byte[],Java 数组的最大长度为Integer.MAX_VALUE。
  • 使用fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);见this answer

标签: java url inputstream nio


【解决方案1】:

使用长版:

long remain = connection.getContentLengthLong();

提示:如果可以将文件压缩为一小部分,则可以发送相应的 Accept 标头,并可选择将流包装在 GZipInputStream 中。

【讨论】:

    【解决方案2】:

    尝试将if (remain &lt; 0)修改为if (remain &lt;= 0)

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多