2016-09-29 58 views
1

我有一個下載和解壓縮文件的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(); 
     ActivityOutput.setText(ActivityOutput.getText()+"\nUpdate size(compressed): "+max+" bytes"); 
     BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(getCWDir()+"\\update.zip"))); 
     byte[] buffer = new byte[32768]; 
     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(); 
     ActivityOutput.setText(ActivityOutput.getText()+"\nDownload Compete!"); 
    } 

    private void unzip() throws IOException{ 
     File tempLoc = new File(getCWDir()+"\\update"); 
     if(!tempLoc.exists()){ 
      tempLoc.mkdir(); 
     } 
     int BUFFER = 2048; 
     BufferedOutputStream dest = null; 
     BufferedInputStream is = null; 
     ZipFile zipfile = new ZipFile(getCWDir()+"\\update.zip"); 
     Enumeration e = zipfile.entries(); 
     new File(getCWDir()+"\\update\\").mkdir(); 
     while(e.hasMoreElements()){ 
      ZipEntry entry = (ZipEntry)e.nextElement(); 
      ActivityOutput.setText(ActivityOutput.getText()+"\nExtracting: "+entry); 
      if(entry.isDirectory()){ 
       new File(getCWDir()+"\\update\\"+entry.getName()).mkdir(); 
      } else { 
       new File(getCWDir()+"\\update\\"+entry.getName()).createNewFile(); 
       is = new BufferedInputStream(zipfile.getInputStream(entry)); 
       byte[] data = new byte[BUFFER]; 
       FileOutputStream fos = new FileOutputStream(getCWDir()+"\\update\\"+entry.getName()); 
       dest = new BufferedOutputStream(fos, BUFFER); 
       int count; 
       while((count = is.read(data, 0, BUFFER)) != -1){ 
        dest.write(data, 0, count); 
       } 
       dest.flush(); 
       dest.close(); 
       is.close(); 
      } 
     } 
    } 

的事情是在這之後我想刪除文件,但他們仍然在使用,我無法執行刪除功能。我找不到問題。我可以得到一些幫助嗎?

+0

我想你想看到這一點: http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java – GavinF

回答

3

我想你應該在你的程序結束時關閉壓縮文件:

zipFile.close(); 
1

謝謝漫步者! 關閉zipfile後問題解決。

  dest.close(); 
      is.close(); 
     } 
    } 
    zipfile.close(); 
}