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

时间:2014-05-28 19:53:23

标签: java unzip

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

  1. Meow.zip
    • File.txt
    • Program.exe
    • 文件夹
      • Resource.xml
      • AnotherFolder
        • OtherStuff
          • MoreResource.xml
  2. 我到处都看,但找不到任何可行的东西。 提前谢谢!

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:1)

您的朋友是ZipFileZipInputStrem上课。