Java:使用多个子目录提取zip文件 [英] Java: Extracting zip file with multiple subdirectories

查看:113
本文介绍了Java:使用多个子目录提取zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.zip(Meow.zip),它有多个文件和文件夹,如此

I have a .zip(Meow.zip) and it has multiple files and folders, like so


  1. Meow.zip


    • File.txt

    • Program.exe

    • 文件夹


      • Resource.xml

      • AnotherFolder


        • OtherStuff


          • MoreResource.xml

  1. Meow.zip
    • File.txt
    • Program.exe
    • Folder
      • Resource.xml
      • AnotherFolder
        • OtherStuff
          • MoreResource.xml

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

I have looked everywhere but I could not find anything that works. Thanks in advance!

推荐答案

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

Here is a class unzipping files from a zip file and recreating the directory tree as well.

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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆