简体   繁体   中英

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 )? I am trying using NIO, but always the stream end at Integer.MAX_VALUE. My file is 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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