2017-10-10 86 views
0

有誰知道如何使用URL(http://.../File.mp4)從互聯網下載文件?我正在嘗試使用NIO,但總是以Integer.MAX_VALUE結束。我的文件是2.5GB。Java-如何從URL下載文件,大於Integer.MAX_VALUE

我的代碼:

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

歡迎來到Stack Overflow!尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者無益。請參閱:如何創建[mcve]。使用「編輯」鏈接來改善你的*問題* - 不要通過評論添加更多信息。謝謝! – GhostCat

+0

不要鏈接到外部網站 - 在你的問題中提供示例代碼! – GhostCat

+0

我懷疑你正在使用'HttpURLConnection'或者某物。類似的使用「ByteArrayInputStream」。這反過來使用'byte []',Java數組的最大長度爲'Integer.MAX_VALUE'。 – Thomas

回答

0

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

+0

這不提供答案題。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/17580908) – Assafs

1

使用長版本:

long remain = connection.getContentLengthLong(); 

提示:如果文件可以送達壓縮到一小部分,你可以發送一個相應的Accept頭,並且可以選擇將這個流封裝在一個GZipInputStream中。