Java如何将zip文件转换为带有文件夹和文件的常规java.io.File [英] Java how to turn zip file into regular java.io.File with folders and files

查看:85
本文介绍了Java如何将zip文件转换为带有文件夹和文件的常规java.io.File的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究将压缩文件转换为常规java.io.File的方法,其中所有文件和文件夹的顺序与zip中的顺序相同.基本上,我只想解压缩压缩文件而不将其内容复制到新目的地.到目前为止,我已经想出了此功能,但仅当zip中没有文件夹时,该功能才能很好地工作.zip中的文件不能是目录,否则我的功能将不起作用,这就是问题所在.
这是我的功能:

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. 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. Files in zip cant be directories or my function will not work and that is the problem.
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;
    }

如何处理zip格式的文件夹?还是有比将zip转换成java.io.File更好的方法呢?
请帮忙!

How can I handle the folders in zip? Or if there is a better way to turn zip into java.io.File than how?
Please help!

推荐答案

找到目录后,您只需要多一点即可设置目录.在复制文件之前使用一行 newFile.mkdirs()创建所需的目录,或者在 entry.isDirectory():

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():

//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();

上述3行比较好,因为它可以复制空目录,而仅添加 newFile.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.

Java NIO提供了一种执行相同解压缩操作的好方法,这是一个示例:

Java NIO provides a nice way of doing the same unzip operation, here is an example:

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);
    }
}

这篇关于Java如何将zip文件转换为带有文件夹和文件的常规java.io.File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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