java 导出zip文件实例_Java如何实现导出ZIP压缩包 Java实现导出ZIP压缩包代码示例...

Java如何实现导出ZIP压缩包?本篇文章小编给大家分享一下Java实现导出ZIP压缩包代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

代码如下:

import org.apache.commons.io.FileUtils;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

/**

* @author wx

* @date 2020/10/29 5:19 下午

*/

public class FileZipUtil {

private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception {

//如果当前的是文件夹,则进行进一步处理

if (file.isDirectory()) {

//得到文件列表信息

File[] fileArray = file.listFiles();

if (fileArray == null) {

return;

}

//将文件夹添加到下一级打包目录

zip.putNextEntry(new ZipEntry(dir + "/"));

dir = dir.length() == 0 ? "" : dir + "/";

//递归将文件夹中的文件打包

for (File f : fileArray) {

handlerFile(zip, f, dir + f.getName());

}

} else {

//当前的是文件,打包处理

//文件输入流

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

ZipEntry entry = new ZipEntry(dir);

zip.putNextEntry(entry);

zip.write(FileUtils.readFileToByteArray(file));

IOUtils.closeQuietly(bis);

zip.flush();

zip.closeEntry();

}

}

private static byte[] createZip(String sourceFilePath) throws Exception{

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

ZipOutputStream zip = new ZipOutputStream(outputStream);

//将目标文件打包成zip导出

File file = new File(sourceFilePath);

handlerFile(zip, file,"");

IOUtils.closeQuietly(zip);

return outputStream.toByteArray();

}

public static void exportZip(HttpServletResponse response, String sourceFilePath) {

//文件名以时间戳作为前缀

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

String filePrefix = sdf.format(new Date());

String downloadName = filePrefix + ".zip";

//将文件进行打包下载

try {

OutputStream out = response.getOutputStream();

//接收压缩包字节

byte[] data = createZip(sourceFilePath);

response.reset();

response.addHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Expose-Headers", "*");

response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);

response.addHeader("Content-Length", "" + data.length);

response.setContentType("application/octet-stream;charset=UTF-8");

IOUtils.write(data, out);

out.flush();

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

客户端调用方法:

@GetMapping("/exportFile")

public Result exportFile(HttpServletResponse response) {

//第二个参数为:要压缩文件的地址

FileZipUtil.exportZip(response, "/Users/Downloads");

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值