2014-01-16 65 views
-3

使用Java下載Zip文件時,打開時顯示無法打開。 想知道什麼是pblm? 是因爲內存少嗎?使用Java下載後ZipFile損壞

這裏是下載zipFiles

try { 
    for(int i=0;i<URL_LOCATION.length;i++) { 
     url = new URL(URL_LOCATION[i]); 
     connection = url.openConnection(); 
     stream = new BufferedInputStream(connection.getInputStream()); 
     int available = stream.available(); 
     b = new byte[available]; 
     stream.read(b); 
     File file = new File(LOCAL_FILE[i]); 
     OutputStream out = new FileOutputStream(file); 
     out.write(b); 
     } 
} catch (Exception e) { 
    System.err.println(e.toString()); 
} 

SOLN此代碼:Refered Link是How to download and save a file from Internet using Java?

BufferedInputStream in = null; 
FileOutputStream fout = null; 
try 
{                         
in = new BufferedInputStream(new URL(urlString).openStream()); 
fout = new FileOutputStream(filename); 
byte data[] = new byte[1024]; 
int count; 
while ((count = in.read(data, 0, 1024)) != -1) 
{ 
fout.write(data, 0, count); 
} 
} 
finally 
{ 
if (in != null) 
in.close(); 
if (fout != null) 
fout.close(); 
} 
+0

您使用Java創建壓縮文件?分享代碼。 –

+0

耶使用zipFile並試圖ZipInputStream也。我已經在wampserver zipFiles。想要使用zipFile下載該文件。 – raja

+0

添加一些代碼,用堆棧跟蹤請 –

回答

2

您正在使用可用的() - 調用來確定如何讀取的字節數。這是公然錯誤的(詳情請參閱InputStream的javadoc)。 available()僅告訴您關於立即可用的數據,而不是關於實際流長度。

您需要一個循環並從流中讀取,直到它返回-1(對於EndOfStream)爲讀取的字節數。

我建議您查看有關流教程:http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

+0

也沒有嘗試過。不工作。爲什麼下載的zip文件被破壞?無法打開? – raja