2011-11-04 55 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

相关问题