Java-如何从URL下载文件,大于Integer.MAX_VALUE



有人知道如何使用URL(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;
        }
    }

使用长版本:

long remain = connection.getContentLengthLong();

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

尝试将if (remain < 0)修改为if (remain <= 0)

最新更新