简体   繁体   English

Java如何将zip文件转换为带有文件夹和文件的常规java.io.File

[英]Java how to turn zip file into regular java.io.File with folders and files

I am working on method that will turn zipped file into regular java.io.File with all files and folders in same order as in zip.我正在研究将压缩文件转换为常规 java.io.File 的方法,其中所有文件和文件夹的顺序与 zip 中的顺序相同。 Basically I just want to unzip zipped file without copying its content into new destination.基本上我只想解压缩压缩文件而不将其内容复制到新目的地。 I have already come up with this function that so far works pretty well but only if there are no folders in zip.我已经提出了这个功能,到目前为止效果很好,但前提是 zip 中没有文件夹。 Files in zip cant be directories or my function will not work and that is the problem. zip 中的文件不能是目录,否则我的功能将无法工作,这就是问题所在。
Here is my function:这是我的功能:

File unzip(File zip) throws IOException
    {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zip));
        
        //helper directory to store files into while program is running!
        File helperDir = Files.createDirectories(Paths.get("zipFile")).toFile();  
        //helperDir.deleteOnExit();
        
        byte[] buffer = new byte[1024];
        for (ZipEntry entry; (entry = zis.getNextEntry()) != null; )
        {
            if (!entry.isDirectory()) //true if file in zip is not a folder
            {
                File newFile = new File(helperDir, entry.getName());
                //newFile.deleteOnExit();
                
                FileOutputStream fos = new FileOutputStream(newFile);
                for (int len = zis.read(buffer); len > 0; len = zis.read(buffer))
                    fos.write(buffer, 0, len);
                fos.close();
            }
            else
            {
                //What to do if there are folders in zip...
            }
        }
        
        zis.close();
        return helperDir;
    }

How can I handle the folders in zip?如何处理 zip 中的文件夹? Or if there is a better way to turn zip into java.io.File than how?或者,是否有比如何更好的方法将 zip 转换为 java.io.File?
Please help!请帮忙!

You only need a little bit more to setup the directory once you have found one.找到目录后,您只需要多做一点就可以设置目录。 Either create the required dirs using one line newFile.mkdirs() just before file copy, or make the directory structure in the else when entry.isDirectory() :要么在文件复制之前使用一行newFile.mkdirs()创建所需的目录,要么在entry.isDirectory()时在 else 中创建目录结构:

//What to do if there are folders in zip...
System.out.println("Reading dir  "+entry.getName());
File newDir = new File(helperDir, entry.getName());
newDir.mkdirs();

The above 3 lines is better as it reproduces empty directories, whereas just adding newFile.mkdirs() only creates directories which have files in them.上面 3 行更好,因为它重现了空目录,而仅添加newFile.mkdirs()只会创建其中包含文件的目录。

Java NIO provides a nice way of doing the same unzip operation, here is an example: Java NIO 提供了一个很好的方式来做同样的解压操作,下面是一个例子:

public static void unzip(Path zip, Path dir) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(zip)) {
        for (Path root : fs.getRootDirectories()) {
            BiPredicate<Path, BasicFileAttributes> foreach = (p,a) -> {
                copy(p,a, Path.of(dir.toString(), p.toString()));
                return false;
            };
            Files.find(root, Integer.MAX_VALUE, foreach).count();
        }
    }
    System.out.println("UNZIPPED "+zip +" to "+dir);
}
private static void copy(Path from, BasicFileAttributes a, Path target)  {
    System.out.println("Copy "+(a.isDirectory() ? "DIR " : "FILE")+" => "+target);
    try {
        if (a.isDirectory())
            Files.createDirectories(target);
        else if (a.isRegularFile())
            Files.copy(from, target, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM