Java对文件/文件夹进行压缩或解压缩

🍇压缩指定目录下的文件/文件夹


/**
 * 压缩工具类
 */
@Slf4j
public class ZipUtils {

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩文件夹
     *
     * @param zipFileName  打包后文件的名称,含路径
     * @param sourceFolder 需要打包的文件夹或者文件的路径
     * @param zipPathName  打包目的文件夹名,为空则表示直接打包到根
     */
    public static void zip(String zipFileName, String sourceFolder, String zipPathName) throws Exception {
        ZipOutputStream out = null;
        try {
            File zipFile = new File(zipFileName);
            FileUtil.mkdir(zipFile.getParent());
            FileOutputStream outputStream = new FileOutputStream(zipFile);
            out = new ZipOutputStream(outputStream);
            if (StringUtils.isNotBlank(zipPathName)) {
                zipPathName = FilenameUtils.normalizeNoEndSeparator(zipPathName, true) + "/";
            } else {
                zipPathName = "";
            }
            zip(out, sourceFolder, zipPathName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 压缩文件夹
     *
     * @param zipFile 打包后文件的名称,含路径
     * @param source  需要打包的文件夹或者文件的路径
     */
    public static void zip(String zipFile, String source) throws Exception {
        File file = new File(source);
        zip(zipFile, source, file.isFile() ? StringUtils.EMPTY : file.getName());
    }

    /**
     * 压缩文件夹
     *
     * @param zipFile a {@link java.io.File} object.
     * @param source  a {@link java.io.File} object.
     */
    public static void zip(File zipFile, File source) throws Exception {
        zip(zipFile.getAbsolutePath(), source.getAbsolutePath());
    }

    private static void zip(ZipOutputStream zos, String file, String pathName) throws IOException {
        File file2zip = new File(file);
        if (file2zip.isFile()) {
            zos.putNextEntry(new ZipEntry(pathName + file2zip.getName()));
            IOUtils.copy(new FileInputStream(file2zip.getAbsolutePath()), zos);
            zos.flush();
            zos.closeEntry();
        } else {
            File[] files = file2zip.listFiles();
            if (ArrayUtils.isNotEmpty(files)) {
                for (File f : files) {
                    if (f.isDirectory()) {
                        zip(zos, FilenameUtils.normalizeNoEndSeparator(f.getAbsolutePath(), true),
                                FilenameUtils.normalizeNoEndSeparator(pathName + f.getName(), true) + "/");
                    } else {
                        FileInputStream inputStream = new FileInputStream(f.getAbsolutePath());
                        zos.putNextEntry(new ZipEntry(pathName + f.getName()));
                        IOUtils.copy(inputStream, zos);
                        inputStream.close();
                        zos.flush();
                        zos.closeEntry();
                    }
                }
            }else{
                // 空文件夹的处理
                zos.putNextEntry(new ZipEntry(pathName + "/"));
                // 没有文件,不需要文件的copy
                zos.closeEntry();
            }
        }
    }


    private static ZipArchiveInputStream getZipFile(File zipFile) throws Exception {
        return new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipFile)), "GBK");
    }

测试

ZipUtils.zip("F:/测试a.zip", "F:/测试nh");

🍇将压缩包解压到指定目录


public class UnZipUtils {

    public static final String EXT = ".zip";
    private static final String BASE_DIR = "";
    private static final String PATH = File.separator;
    private static final int BUFFER = 1024;

    /**
     * 文件 解压缩
     *
     * @param srcPath 源文件路径
     * @throws Exception
     */
    public static void decompress(String srcPath) throws Exception {
        File srcFile = new File(srcPath);
        decompress(srcFile);
    }

    /**
     * 解压缩
     *
     * @param srcFile
     * @throws Exception
     */
    public static void decompress(File srcFile) throws Exception {
        String basePath = srcFile.getParent();
        decompress(srcFile, basePath);
    }

    /**
     * 解压缩
     *
     * @param srcFile
     * @param destFile
     * @throws Exception
     */
    public static void decompress(File srcFile, File destFile) throws Exception {
        CheckedInputStream cis = new CheckedInputStream(new FileInputStream(srcFile), new CRC32());
        ZipInputStream zis = new ZipInputStream(cis, Charset.forName("GBK"));
        decompress(destFile, zis);
        zis.close();

    }

    /**
     * 解压缩
     * @param srcFile
     * @param destPath
     * @throws Exception
     */
    public static void decompress(File srcFile, String destPath) throws Exception {
        decompress(srcFile, new File(destPath));
    }

    /**
     * 文件 解压缩
     * @param srcPath  源文件路径
     * @param destPath 目标文件路径
     * @throws Exception
     */
    public static void decompress(String srcPath, String destPath) throws Exception {
        File srcFile = new File(srcPath);
        decompress(srcFile, destPath);
    }

    /**
     * 文件 解压缩
     * @param destFile 目标文件
     * @param zis      ZipInputStream
     * @throws Exception
     */
    private static void decompress(File destFile, ZipInputStream zis) throws Exception {
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            // 文件
            String dir = destFile.getPath() + File.separator + entry.getName();
            File dirFile = new File(dir);
            // 文件检查
            fileProber(dirFile);
            if (entry.isDirectory()) {
                dirFile.mkdirs();
            } else {
                decompressFile(dirFile, zis);
            }
            zis.closeEntry();
        }
    }

    /**
     * 文件探针
     * 当父目录不存在时,创建目录!
     * @param dirFile
     */
    private static void fileProber(File dirFile) {
        File parentFile = dirFile.getParentFile();
        if (!parentFile.exists()) {
            // 递归寻找上级目录
            fileProber(parentFile);
            parentFile.mkdir();
        }
    }

    /**
     * 文件解压缩
     *
     * @param destFile 目标文件
     * @param zis      ZipInputStream
     * @throws Exception
     */
    private static void decompressFile(File destFile, ZipInputStream zis) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            bos.write(data, 0, count);
        }
        bos.close();
    }
}
UnZipUtils.decompress("F:/test/测试a.zip", "F:/test/");
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值