解压特定zip压缩文件中特定文件,Java

x33g5p2x  于2022-06-30 转载在 Java  
字(1.0k)|赞(0)|评价(0)|浏览(316)

解压特定zip压缩文件中指定文件,Java

有些时候,zip压缩文件特别大动辄几大GB,但是只想要其中某一个特定文件,此时就完全没必要把全量文件都解压出来,只需解压指定文件即可。

public static void decompress(String targetFileName, String srcPath, String destPath) throws Exception {
        File file = new File(srcPath);
        if (!file.exists()) {
            throw new RuntimeException(srcPath + "不存在");
        }

        ZipFile zf = new ZipFile(file);
        Enumeration entries = zf.entries();
        ZipEntry entry;
        while (entries.hasMoreElements()) {
            entry = (ZipEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.endsWith(targetFileName)) {
                continue;
            }

            File dir = new File(destPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File f = new File(dir + File.separator + targetFileName);
            if (!f.exists()) {
                f.createNewFile();
            }

            InputStream is = zf.getInputStream(entry);
            FileOutputStream fos = new FileOutputStream(f);

            int count;
            byte[] buffer = new byte[1024 * 8];
            while (true) {
                count = is.read(buffer);
                if (count == -1) {
                    break;
                }

                fos.write(buffer, 0, count);
            }

            is.close();
            fos.close();
        }
    }

上面功能函数首先从srcPath加载zip压缩文件,然后对zip压缩文件里面包含的每个文件进行过滤筛选,搜索到名字为targetFileName的文件后,将其解压到destPath目录文件夹下。

相关文章

微信公众号

最新文章

更多