Java压缩文件/文件夹

ZipOutputStream流、递归压缩。

        在关闭ZipOutputStream流之前,需要先调用flush()方法,强制将缓冲区所有的数据输出,以避免解压文件时出现压缩文件已损坏的现象。

/**
 * @param source    待压缩文件/文件夹路径
 * @param destination   压缩后压缩文件路径
 * @return
 */
public static boolean toZip(String source, String destination) {
    try {
        FileOutputStream out = new FileOutputStream(destination);
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        File sourceFile = new File(source);

        // 递归压缩文件夹
        compress(sourceFile, zipOutputStream, sourceFile.getName());

        zipOutputStream.flush();
        zipOutputStream.close();
    } catch (IOException e) {
        System.out.println("failed to zip compress, exception");
        return false;
    }
    return true;
}

private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {
    byte[] buf = new byte[1024];
    if(sourceFile.isFile()){
        // 压缩单个文件,压缩后文件名为当前文件名
        zos.putNextEntry(new ZipEntry(name));
        // copy文件到zip输出流中
        int len;
        FileInputStream in = new FileInputStream(sourceFile);
        while ((len = in.read(buf)) != -1){
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        in.close();
    } else {
        File[] listFiles = sourceFile.listFiles();
        if(listFiles == null || listFiles.length == 0){
            // 空文件夹的处理(创建一个空ZipEntry)
            zos.putNextEntry(new ZipEntry(name + "/"));
            zos.closeEntry();
        }else {
            // 递归压缩文件夹下的文件
            for (File file : listFiles) {
                compress(file, zos, name + "/" + file.getName());
            }
        }
    }
}
    原文作者:零点冰.
    原文地址: https://blog.csdn.net/weixin_37672801/article/details/123647870
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞