簡體   English   中英

Java-如何從URL下載大於Integer.MAX_VALUE的文件

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

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

使用長版本:

long remain = connection.getContentLengthLong();

提示:如果可以將文件壓縮為小部分,則可以發送相應的Accept標頭,還可以選擇將流包裝在GZipInputStream中。

嘗試將if (remain < 0)修改為if (remain <= 0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM