Java:使用多个子目录提取zip文件

8
我有一个名为Meow.zip的压缩文件,里面包含多个文件和文件夹,如下所示:
  1. Meow.zip
    • File.txt
    • Program.exe
    • Folder
      • Resource.xml
      • AnotherFolder
        • OtherStuff
          • MoreResource.xml
我已经四处寻找,但都没有找到有效的方法。提前感谢你!

你尝试过在谷歌上搜索“java提取zip文件”吗?第一个链接上有一个教程。 - David
@David,这现在是谷歌上“java zip get files from subdirectory”的第一个链接。 - John Biddle
2个回答

13

这是一个从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


谢谢,这个完美地解决了我的问题。我之前尝试了其他方法,但只能处理一个子文件夹而已。 - user3685130
压缩和解压数据使用Java APIs 不错的关于zip提取/压缩的阅读。 [Compressing and Decompressing Data Using Java APIs] (http://www.oracle.com/technetwork/articles/java/compress-1565076.html) - Chacko
@ChackoMathew 链接无效 - johnnieb

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接