Springboot打包文件夹为ZIP并导出

在springboot下打包文件夹并导出zip包代码如下

    @ApiOperation(value="导出接口")
    @RequestMapping(value="/export",method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException{
        OutputStream out = response.getOutputStream();
        try {
            response.setCharacterEncoding("UTF-8");
            String path = searchService.export();
            File file = new File(path);
            byte[] data = getStream(path);
            // 压缩包名称
            String downloadName = file.getName();
            response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
         
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
你可以使用Java的ZipOutputStream类来实现将文件夹打包ZIP导出的功能。具体实现步骤如下: 1. 首先,你需要使用Java的File类找到需要打包文件夹,将其所有文件和子文件夹都遍历出来。 2. 然后,你需要使用Java的ZipOutputStream类创建一个ZIP文件输出流,并将其与要生成的ZIP文件关联起来。 3. 接下来,你需要逐个将需要打包文件文件夹添加到ZIP文件中。对于文件夹,你需要递归地将其下的所有文件和子文件夹都添加到ZIP文件中。对于文件,你需要使用ZipEntry类创建一个ZIP文件条目,并将其添加到ZIP文件输出流中。 4. 最后,你需要关闭ZIP文件输出流。 下面是一个示例代码,假设你需要打包名为“myFolder”的文件夹: ```java import java.io.*; import java.util.zip.*; public class ZipFolder { public static void main(String[] args) throws Exception { String sourceFolder = "myFolder"; // 需要打包文件夹 String zipFile = "myArchive.zip"; // 生成的ZIP文件名 FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); zipFolder(sourceFolder, sourceFolder, zos); zos.close(); fos.close(); System.out.println("ZIP文件已生成:" + zipFile); } private static void zipFolder(String baseFolder, String sourceFolder, ZipOutputStream zos) throws Exception { File folder = new File(sourceFolder); for (File file : folder.listFiles()) { if (file.isDirectory()) { zipFolder(baseFolder, file.getAbsolutePath(), zos); } else { String entryName = file.getAbsolutePath().substring(baseFolder.length() + 1); ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } } } } ``` 这个示例代码将会打包名为“myFolder”的文件夹,并生成名为“myArchive.zip”的ZIP文件。你可以根据自己的需要修改代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值