2017-10-10 108 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中。