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

网上很多导出的都试了很多 多少有点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();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用Java的压缩库来将文件打包zip文件,并将其发送给前端。下面是一个简单的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipFileSender { public static void main(String[] args) { String filePath = "path_to_file"; String zipFilePath = "path_to_zip_file"; File fileToZip = new File(filePath); try { FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zos = new ZipOutputStream(fos); addToZip(fileToZip, fileToZip.getName(), zos); zos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } private static void addToZip(File file, String fileName, ZipOutputStream zos) throws IOException { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } } ``` 在上面的示例中,我们创建了一个`ZipFileSender`类,它将提供的文件(`filePath`)打包为一个zip文件(`zipFilePath`)。我们使用`java.util.zip.ZipOutputStream`类来创建zip文件并添加文件zip文件中。`addToZip`方法用于将文件添加到zip文件中。最后,我们使用`FileOutputStream`类将zip文件发送给前端。运行以上代码,将会在指定路径生名为`zipFilePath`的zip文件,你可以将其发送给前端

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值