2014-09-03 53 views
0

我有一个zip文件(x.zip),其中有另一个zip文件(y.zip)。我需要在y.zip中读取一个文件。我如何迭代两个zip文件来读取文件?如何使用ZipEntry读取位于另一个zip文件中的一个zip文件中的数据?

我用来迭代x.zip来读取y.zip的代码如下。

在代码中,“zipX”代表“x.zip”。当遇到“y.zip”时,它满足代码中的“if条件”。在这里,我需要遍历“zipEntry”并在其中读取文件。

这是如何实现的?

private void getFileAsBytes(String path, String name) throws IOException { 
     ZipFile zipX = new ZipFile(path); 
     Enumeration<? extends ZipEntry> entries = zipX.entries(); 
     while (entries.hasMoreElements()) 
     { 
      ZipEntry zipEntry = entries.nextElement(); 
      if(zipEntry.getName().contains(name) && zipEntry.getName().endsWith(".zip")) { 
       InputStream is; 
       is = zipX.getInputStream(zipEntry); 
       // Need to iterate through zipEntry here and read data from a file inside it. 
       break; 
      } 
     } 
     zipX.close(); 
} 
+0

怎么样用递归方法,直到结束? – Vikram 2014-09-03 22:18:49

+1

在['ZipInputStream'](http://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipInputStream.html)中包装内部InputStream并将其读为普通zip文件“... – MadProgrammer 2014-09-03 22:19:07

+0

@MadProgrammer如果Y.zip里面有另一个zip文件呢?他需要继续继续if/else块。 – Vikram 2014-09-03 22:24:15

回答

1

根据ZipFile docs,你需要传入一个File对象或文件路径; InputStream不受支持。

考虑到这一点,你可以说的InputStream写入到一个临时文件,然后传递文件到您现有的方法:

... 
is = zipX.getInputStream(zipEntry); 
File tmpDir = new File(System.getProperty("java.io.tmpdir")); 
//For production, generate a unique name for the temp file instead of using "temp"! 
File tempFile = createTempFile("temp", "zip", tmpDir); 
this.getFileAsBytes(tempFile.getPath(), name); 
break; 
... 
相关问题