简体   繁体   English

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

[英]Java- How to download file from URL, larger than Integer.MAX_VALUE

Does anybody knows how to download file from internet, using URL ( http://.../File.mp4 )? 有人知道如何使用URL( http://.../File.mp4 )从Internet下载文件吗? I am trying using NIO, but always the stream end at Integer.MAX_VALUE. 我正在尝试使用NIO,但是流总是以Integer.MAX_VALUE结尾。 My file is 2.5GB. 我的文件是2.5GB。

My code: 我的代码:

    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;
        }
    }

Use the long version: 使用长版本:

long remain = connection.getContentLengthLong();

Tip: if the file could be served compressed to a fraction, you could send a corresponding Accept header and optionally wrap the stream in a GZipInputStream. 提示:如果可以将文件压缩为小部分,则可以发送相应的Accept标头,还可以选择将流包装在GZipInputStream中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM