2015-11-19 113 views
0

我只是試圖從一個網站下載文件,我檢查了網址,一切似乎都很好,但是當我試圖做它像描述它打印出我的更新大小是-1 Bytes,不知道這是爲什麼發生。下載一個ZIP文件與Java得到它損壞

如果有人有解決方案,我會很高興在這裏。

我的代碼:

private void downloadFile(String link) throws MalformedURLException, IOException 
{ 
    URL url = new URL(link); 
    URLConnection conn = url.openConnection(); 
    InputStream is = conn.getInputStream(); 
    long max = conn.getContentLength(); 
    outText.setText(outText.getText()+"\n"+"Downloding file...\nUpdate Size(compressed): "+max+" Bytes"); 
    System.out.println("Update Size --> " + max + " Bytes"); 
    BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip"))); 
    byte[] buffer = new byte[32 * 1024]; 
    int bytesRead = 0; 
    int in = 0; 
    while ((bytesRead = is.read(buffer)) != -1) { 
     in += bytesRead; 
     fOut.write(buffer, 0, bytesRead); 
    } 
    fOut.flush(); 
    fOut.close(); 
    is.close(); 
    outText.setText(outText.getText()+"\nDownload Complete!"); 
} 

非常感謝已經:)

回答

0

The javadoc是你的朋友:

返回: 資源的內容長度此連接的URL引用,-1如果內容長度未知,或者內容長度大於Integer.MAX_VALUE

(重點煤礦)

+0

嗯,我想我沒有釘子的問題有......對不起,我的錯。其實我的問題是如何修復損壞的ZiP文件...如果你也可以回答我這個問題,那太棒了! :) – njoye

+0

@njoye在你的問題中沒有什麼關於這個的。請修復它。 – EJP

+0

@njoye你的代碼對我來說看起來很好。你確定這個URL是一個zip文件的URL嗎?例如,如果將下載的文件作爲文本文件打開,會發生什麼情況? –