java 用MultipartFile接收zip文件,使用apache commons compress进行高效解压,解压成File对象

以下是用Java代码接收zip文件并解压:


import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Controller
public class FileUploadController {
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取上传的zip文件流
        InputStream inputStream = file.getInputStream();
        // 创建ZipArchiveInputStream对象
        ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(inputStream);
        // 创建解压后的文件目录
        File destDir = new File("/Users/dest/");
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        // 循环遍历压缩文件中的所有文件
        ArchiveEntry archiveEntry;
        while ((archiveEntry = zipInputStream.getNextEntry()) != null) {
            String entryName = archiveEntry.getName();
            String[] entryNameParts = entryName.split("/");
            String fileName = entryNameParts[entryNameParts.length - 1];
            File entryFile = new File(destDir + "/" + fileName);
            // 如果是文件夹,就创建文件夹
            if (entryName.endsWith("/")) {
                entryFile.mkdir();
            } else {
                // 创建文件输出流
                OutputStream outputStream = new FileOutputStream(entryFile);
                // 将压缩文件解压到指定文件
                byte[] buffer = new byte[1024];
                int len;
                while ((len = zipInputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                // 关闭文件输出流
                outputStream.close();
            }
        }
        // 关闭ZipInputStream
        zipInputStream.close();
        return "success";
    }
}

该代码使用了Spring框架,接收上传的zip文件,并将其解压到指定目录。其中利用了Apache Commons Compress库实现高效解压。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值