2014-12-24 35 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