java - 使用 Java ZipFile 类解压缩 ZIP 文件

标签 java zip compression

我在使用 Java 解压缩 ZIP 文件时遇到问题。方法如下。

文件解压缩后文件结构是正确的,这意味着 ZIP 文件中的目录没有问题,但文件输出的长度为零。

我检查了 ZIP 文件,看压缩是否正确,那里都是正确的。

如果有人看到我遗漏的东西,请...

public static void unzip ( File zipfile, File directory ) throws IOException {
  ZipFile zip = new ZipFile ( zipfile );
  Enumeration<? extends ZipEntry> entries = zip.entries ();

  while ( entries.hasMoreElements () ) {
    ZipEntry entry = entries.nextElement ();
    File file = new File ( directory, entry.getName () );

    if ( entry.isDirectory () ) {
      file.mkdirs ();
    }
    else {
      file.getParentFile ().mkdirs ();

      ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );
      OutputStream out = new FileOutputStream ( file );
      byte[] buffer = new byte[4096];
      int readed = 0;

      while ( ( readed = in.read ( buffer ) ) > 0 ) {
        out.write ( buffer, 0, readed );
        out.flush ();
      }

      out.close ();
      in.close ();
    }
  }

  zip.close ();
}

更多...显然 getInputStream ( entry ) 方法返回零字节,不知 Prop 体原因。

最佳答案

ZipFile已经解压缩条目的数据,也不需要使用 ZipInputStream

代替:

ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );

使用:

InputStream in = zip.getInputStream ( entry );

ZipInputStream 也可用于解压缩 ZIP 文件。您获得零长度流的原因是因为使用 ZipInputStream 您需要调用 getNextEntry() 来读取 ZIP 中的第一个文件。

关于java - 使用 Java ZipFile 类解压缩 ZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9829729/

相关文章:

Linux zip命令生成带有两个成功数字密码的归档文件

java - 使用 Java Runtime 压缩并存档文件夹中的文件

python - 在 Raspberry Pi 上保存图像流的最快方法

java - 从解析数据库 Android 中提取 INT

Java Regex递归获取特定单词前后的11个单词

java - Spring 中的 PROPAGATION_REQUIRED 行为?

java - Mac 中的文件关联

php - DOCX 编码问题

java - ZipFile InputStreams 线程安全吗?

spring-boot - 如何在spring boot(使用netty服务器)中启用websocket消息压缩deflate(使用rsocket协议(protocol))