2011-11-04 90 views
0

我有一個愚蠢的問題,我一直無法弄清楚。誰能幫我? 我的代碼:嘗試使用java.util.zip.ZipFile解壓縮存檔時出現FileNotFoundException

String zipname = "C:/1100.zip"; 
    String output = "C:/1100"; 
    BufferedInputStream bis = null; 
    BufferedOutputStream bos = null; 
    try { 
     ZipFile zipFile = new ZipFile(zipname); 
     Enumeration<?> enumeration = zipFile.entries(); 
     while (enumeration.hasMoreElements()) { 
      ZipEntry zipEntry = (ZipEntry) enumeration.nextElement(); 
      System.out.println("Unzipping: " + zipEntry.getName()); 
      bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)); 
      int size; 
      byte[] buffer = new byte[2048]; 

它不會創建一個文件夾,但調試顯示正在生成的所有內容。 爲了創建一個文件夾,我使用的代碼

if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception

  bos = new BufferedOutputStream(new FileOutputStream(new File(outPut))); 
      while ((size = bis.read(buffer)) != -1) { 
       bos.write(buffer, 0, size); 
      } 
     } 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } finally { 
     bos.flush(); 
     bos.close(); 
     bis.close(); 
    } 

我的zip文件中包含圖片:A.JPG B.JPG ...在同一個層次,我有abc.xml。 我需要解壓縮文件中的內容。 任何幫助在這裏。

回答

0

你的代碼有幾個問題:outPut在哪裏聲明? output不是一個文件,而是一個字符串,所以exists()mkdir()不存在。通過聲明output開始想:

File output = new File("C:/1100"); 

此外,outPut(大P)未聲明。它就像output + File.seprator + zipEntry.getName()

bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName())); 

注意,你不需要通過文件傳遞給FileOutputStream,因爲構造顯示the documentation

此時,如果您的Zip文件不包含目錄,您的代碼應該可以工作。但是,在打開輸出流時,如果zipEntry.getName()具有目錄組件(例如somedir/filename.txt),則打開該流將導致FileNotFoundException,因爲您嘗試創建的文件的父目錄不存在。如果你想能夠處理這樣的zip文件,你會找到你的答案在:How to unzip files recursively in Java?

+0

任何方式,我可以解決它,並感謝你隊友 – Robin

+0

最後我寫了它爲我的博客:http://thaparobin.blogspot .COM/2011/11/java的拆包-zip文件從 - 遠程url.html – Robin

相關問題