java实现文件的压缩及解压

一、前言
最近在项目开发中需要实现文件的压缩及解压功能,以满足某些特定场景的下的需要,因此在这里说下具体实现。

二、实现
1.定义一个工具类ZipUtils,实现文件的压缩及解压,代码如下:

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * ZIP压缩工具
 *
 */
public class ZipUtils {
	 /**
     * 压缩文件/文件夹
     * 若压缩的为文件夹:则压缩包中第一层为该文件夹
     * 若压缩的为文件:则压缩包中第一层为该文件
     *
     * @param srcFilePath 源文件
     * @param zipFilePath zip
     */
    public static void compress(String srcFilePath, String zipFilePath) {
        File src = new File(srcFilePath);
        if (!src.exists()) {
            throw new RuntimeException(srcFilePath + "不存在");
        }
        File zipFile = new File(zipFilePath);
        try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) {
            String baseDir = "";
            compress(src, zos, baseDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	/**
     * 压缩
     *
     * @param src
     * @param zos
     * @param baseDir
     */
    public static void compress(File src, ZipOutputStream zos, String baseDir) {
        if (!src.exists())
            return;
        if (src.isFile()) {
            compressFile(src, zos, baseDir);
        } else if (src.isDirectory()) {
            compressDir(src, zos, baseDir);
        }
    }
    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
        if (!file.exists())
            return;
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[4096];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
        } catch (Exception e) {
        }
    }
    /**
     * 压缩文件夹
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
        if (!dir.exists() || dir.isFile())
            return;
        File[] files = dir.listFiles();
        if (files != null) {
            if (files.length == 0) {
                try {
                    zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                for (File file : files) {
                    compress(file, zos, baseDir + dir.getName() + File.separator);
                }
            }
        }
    }
    /**
     * 解压文件
     *
     * @param zipFilePath
     * @param destDirPath
     */
    public static void unzip(String zipFilePath, String destDirPath) {
        File srcFile = new File(zipFilePath);
        unzip(srcFile, destDirPath);
    }
    /**
     * 解压文件
     *
     * @param srcFile
     * @param destDirPath
     */
    public static void unzip(File srcFile, String destDirPath) {
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        } else if (!srcFile.isFile()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件为文件夹");
        }
        try (ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"))) {
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + File.separator + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    File targetFile = new File(destDirPath + File.separator + entry.getName());
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[4096];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.close();
                    is.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        }
    }
}

接口main方法调用下方法就可以了。

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Java中,MultipartFile是Spring Framework中用于处理文件上传的接口。它提供了一些方法来操作上传的文件。然而,MultipartFile并没有直接提供解压文件的方法。 要解压缩MultipartFile文件,你需要将其转换为普通的Java IO文件类型,然后使用解压缩库来处理文件解压缩的操作。在你的引用中,你提到了一个私有方法 `unzip(MultipartFile file)` ,它使用MultipartFile文件进行解压缩操作。我假设这个方法中的逻辑是正确的。 为了实现解压缩MultipartFile文件的操作,你需要完成以下步骤: 1. 将MultipartFile文件转换为普通的Java IO文件类型。这可以通过创建一个临时文件并将MultipartFile的内容写入该文件实现。你可以使用`file.transferTo()`方法将MultipartFile的内容写入Java IO文件。 2. 调用`unzip()`方法,将Java IO文件作为参数进行解压缩操作。该方法应该返回解压后的文件。 3. 将解压后的文件再次转换为MultipartFile类型,以便进一步处理或上传。 但是,请注意,将解压后的文件转换回MultipartFile类型并不是一个标准的操作。因为MultipartFile是Spring Framework中特定于文件上传的接口,它通常与文件上传相关的逻辑紧密结合。所以,如果你需要将解压后的文件再次转换为MultipartFile类型,你可能需要自定义一些逻辑来创建一个包含解压文件内容的MultipartFile对象。 综上所述,要在Java解压缩MultipartFile文件,你需要将MultipartFile转换为Java IO文件,然后使用解压缩库对该文件进行解压缩操作。如果需要将解压后的文件再次转换为MultipartFile类型,你可能需要自定义一些逻辑来创建相应的MultipartFile对象。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空下的星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值