2014-12-05 29 views
0

我有一个目录,我用这种方法ZIP:输出拉链目录ByteArrayOutputStream

public byte[] archiveDir(File dir) { 
    try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(bos)) { 
     zipSubDirectory("", dir, zout); 
     return bos.toByteArray(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

private void zipSubDirectory(String basePath, File dir, ZipOutputStream zout) throws IOException { 
    byte[] buffer = new byte[4096]; 
    File[] files = dir.listFiles(); 
    for (File file : files) { 
     if (file.isDirectory()) { 
      String path = basePath + file.getName() + "/"; 
      zout.putNextEntry(new ZipEntry(path)); 
      zipSubDirectory(path, file, zout); 
      zout.closeEntry(); 
     } else { 
      FileInputStream fin = new FileInputStream(file); 
      zout.putNextEntry(new ZipEntry(basePath + file.getName())); 
      int length; 
      while ((length = fin.read(buffer)) > 0) { 
       zout.write(buffer, 0, length); 
      } 
      zout.closeEntry(); 
      fin.close(); 
     } 
    } 
} 

我然后写入字节servlet的输出流。但是,当我收到zip文件时,无法打开“文件格式错误”。如果我将压缩内容输出到FileOutputStream,然后将文件内容发送到servlet的输出流,则它工作正常。那么,这将解决我的问题,但在这种情况下,我将永远不得不删除它的内容发送到servlet的输出流后的临时zip文件。是否有可能只是在记忆中这样做。

+0

“它无法打开” - 这是什么意思?你如何试图打开它? – JimmyB 2014-12-05 11:41:28

+0

@HannoBinder它说,“该文件格式错误”。我更新了我的问题 – user1745356 2014-12-05 12:03:29

回答

2

嗯,

 zipSubDirectory(path, file, zout); 
     zout.closeEntry(); 

应该是:

 zout.closeEntry(); 
     zipSubDirectory(path, file, zout); 

主要错误似乎是ZOUT未关闭/之前冲刷toByteArray被调用。这里尝试与资源有点狡猾。

try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { 
    try ((ZipOutputStream zout = new ZipOutputStream(bos)) { 
     zipSubDirectory("", dir, zout); 
    } 
    return bos.toByteArray(); 
} catch (IOException e) { 
    throw new RuntimeException(e); 
} 
+0

这就像一个魅力。谢谢。 – user1745356 2014-12-05 12:16:07