2014-12-24 36 views
0

guys! 我有问题!我试图下载一个.zip(大小为150 MB),使用此代码从Internet文件:如何用java下载url的.zip文件

public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException { 
    debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL)); 
    try { 
     URL url = new URL(srcURL); 
     HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
     httpConn.setRequestMethod("POST"); 
     httpConn.connect(); 
     in = httpConn.getInputStream(); 
     out = new FileOutputStream(destPath); 
     byte buffer[] = new byte[bufferSize]; 
     int c = 0; 
     while ((c = in.read(buffer)) > 0) { 
      out.write(buffer, 0, c); 
     } 
     out.flush(); 
     debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath)); 
    } catch (IOException e) { 
     debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString())); 
    } finally { 
     try { 
      if (out != null) { 
       out.close(); 
      } 
      if (in != null) { 
       in.close(); 
      } 
     } catch (IOException ex) { 
     } 
    } 
} 

但该文件没有完全下载。 (只有4000字节)。我究竟做错了什么?

+0

你为什么使用http post request?使用此下载http://stackoverflow.com/questions/18872611/download-file-from-server-in-java –

+1

不是说它解决任何问题,但你不应该忽略例外。总是至少打印他们的堆栈跟踪。 – Pshemo

+0

但我在我的程序中没有异常,但文件文件没有完全下载。 –

回答

1
FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE); 

简单的一行。欲了解更多信息,请阅读here

+1

与其中一个注释相同的答案? –

+0

@KonstantinosChalkias如果您觉得此问题已在另一篇文章中得到解答,您应该标记此问题并将其标记为重复,并指定其为重复的帖子。除此之外,评论不是答案,所以这很好。你应该避免在评论部分回答问题,如果你觉得有人可能会盗取它 –

+1

*“试试这个”* - 为什么? – MadProgrammer