java将文件夹和里面的所有文件打包成zip导出

该代码段展示了一个Java方法,用于创建并导出ZIP压缩文件。首先,它创建临时文件夹和多个文本文件,然后使用`fileExportUtils`工具类将这些文件打包成ZIP,最后通过`HttpServletResponseresponse`将ZIP文件作为附件发送给客户端。过程中还包含了文件夹和文件的创建、写入内容、以及删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上很多导出的都试了很多 多少有点BUG,不完善,网上资料自己测试一下 完整导出

免费分享给大家!

public void exportZIP(HttpServletResponse response) {
    File loadFile = null;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        /*2、创建临时文件夹*/
        String path = fileExportUtils.getHomePath();
        String pathTest = "D:\\export";
        //创建文件夹
        loadFile = new File(pathTest + "/压缩包");
        if (!loadFile.exists()) {
            loadFile.mkdirs();
        }
        // 创建车数据文件夹
        File carFile = new File(loadFile.getPath() + "/数据");
        //创建用于存放下车的文件夹
        File xiaCheDir = new File(carFile.getPath() + "/01");
        if (!xiaCheDir.exists()) {
            xiaCheDir.mkdirs();
        }
        File txtFile1 = new File(xiaCheDir.getPath() + "/01下车.txt");
        if (!txtFile1.exists()) {
            txtFile1.createNewFile();
        }
        FileOutputStream fos1 = new FileOutputStream(txtFile1);
        OutputStreamWriter dos1 = new OutputStreamWriter(fos1);
        dos1.write("hello,worldhello,worldhello,worldhello,worldhello,worldhello,worldhello,world");
        dos1.close();
        //创建用于存放下车的文件夹
        File testCheDir = new File(carFile.getPath() + "/02");
        if (!testCheDir.exists()) {
            testCheDir.mkdirs();
        }
        File txtFile2 = new File(testCheDir.getPath() + "/02.txt");
        if (!txtFile2.exists()) {
            txtFile2.createNewFile();
        }
        FileOutputStream fos2 = new FileOutputStream(txtFile2);
        OutputStreamWriter dos2 = new OutputStreamWriter(fos2);
        dos2.write("hello,worldhello,worldhello,worldhello,worldhello,worldhello,worldhello,world");
        dos2.close();

        /*4、loadFile*/
        byte[] data = fileExportUtils.getZip(loadFile.getPath());
        //创建压缩包
        String zipName = loadFile.getName() + ".zip";

        String fileNameURL = URLEncoder.encode(zipName, "UTF-8");
        URLEncoder.encode(zipName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileNameURL + ";" + "filename*=utf-8''" + fileNameURL);

        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        IOUtils.write(data, out);
    } catch (Exception e) {
        log.info("导出文件出错{}",e);
    } finally {
        try {
            //删除file1
            if (loadFile.exists()) {
                //fileExportUtils.deleteDir(loadFile);
            }
            //关闭相应流
            if (null != out) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

导出工具类

/**
 * 删除目录下所有文件
 *
 * @return
 */
public void deleteDir(File directory) throws IOException {
    Path path = Paths.get(directory.getPath());
    try (Stream<Path> walk = Files.walk(path)) {
        walk.sorted(Comparator.reverseOrder())
                .forEach(path1 -> {
                    try {
                        Files.delete(path1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }
}

/**
 * 功能描述: 生成zip文件字节流
 */
public byte[] getZip(String filePath) {
    System.out.println("开始zip所在目录:" + filePath);
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         ZipOutputStream zip = new ZipOutputStream(outputStream)) {
        //将目标文件打包成zip导出
        File file = new File(filePath);
        createZip(zip, file, "");
        zip.close();
        return outputStream.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 创建Zip压缩包
 *
 * @param zip
 * @param file
 * @param dir
 */
public void createZip(ZipOutputStream zip, File file, String dir) {
    byte[] buf = new byte[1024];
    try {
        //如果当前是文件夹则进行迭代处理
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            //将文件夹添加至下一级目录
            zip.putNextEntry(new ZipEntry(dir + "/"));
            dir = dir.length() == 0 ? "" : dir + "/";
            for (int i = 0; i < files.length; i++) {
                createZip(zip, files[i], dir + files[i].getName());
            }
        } else {
            //当前是文件,进行打包处理
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(dir);
            zip.putNextEntry(entry);
            int len = 0;
            while ((len = bis.read(buf)) != -1) {
                zip.write(buf, 0, len);
            }
            bis.close();
            zip.closeEntry();
        }
    } catch (Exception e) {
        try {
            zip.flush();
            zip.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值