Java:提取具有多个子目录的 zip 文件

标签 java unzip

<分区>

我有一个 .zip(Meow.zip),它有多个文件和文件夹,就像这样

  1. 喵喵.zip
    • 文件.txt
    • 程序.exe
    • 文件夹
      • 资源.xml
      • 另一个文件夹
        • 其他东西
          • 更多资源.xml

我到处都找遍了,但找不到任何有用的东西。 提前致谢!

最佳答案

这是一个从 zip 文件解压缩文件并重新创建目录树的类。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ExtractZipContents {

    public static void main(String[] args) {

        try {
            // Open the zip file
            ZipFile zipFile = new ZipFile("Meow.zip");
            Enumeration<?> enu = zipFile.entries();
            while (enu.hasMoreElements()) {
                ZipEntry zipEntry = (ZipEntry) enu.nextElement();

                String name = zipEntry.getName();
                long size = zipEntry.getSize();
                long compressedSize = zipEntry.getCompressedSize();
                System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", 
                        name, size, compressedSize);

                // Do we need to create a directory ?
                File file = new File(name);
                if (name.endsWith("/")) {
                    file.mkdirs();
                    continue;
                }

                File parent = file.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                // Extract the file
                InputStream is = zipFile.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();

            }
            zipFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

来源:http://www.avajava.com/tutorials/lessons/how-do-i-unzip-the-contents-of-a-zip-file.html

关于Java:提取具有多个子目录的 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920684/

相关文章:

javascript - Node 解压。如何制作文件名

php - 解压文件跳过文件夹

Java 线程 GDB

java - 有没有易于使用和编程的日期选择器java swing?

Java 用对象填充 ArrayList?

python - 在 python 中提取 .zip

excel - 如何使用 scala 解压 zip 文件?

iphone - 如何从一个 NSData 对象写入多个文件?

java - Apache Commons Codec Base64 是 sun.misc.BASE64 的直接替代品吗?

java - 即使在一对多关系(JPA/Hibernate)上使用 orphanRemoval=true,孤儿仍保留在数据库中