1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Java对文件夹压缩成zip导出

Java对文件夹压缩成zip导出

时间:2022-07-03 00:22:49

相关推荐

Java对文件夹压缩成zip导出

1、描述:(随手记录一下,方便下次碰到直接复制粘贴)

需求:将文件夹层级结构导出成zip压缩包并导出(我们项目的目录文件夹-文件夹-电子文件)。项目:springboot+mybatis plus

1、将目录结构转化为文件夹结构

2、压缩文件夹并删除原文件夹

3、导出完成并删除原压缩文件

2:service

处理过程

// 设置文件夹时间戳和路径位置SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String format = sdf.format(new Date());// 文件夹的路径,写入服务器的 /tmp 文件夹下String filePath = "/tmp/BI_SQL_" + format;// 导出的zip路径String zipFilePath = "/tmp/BI_SQL_" + format + ".zip";// 导出的zip名字String zipName = "BI_SQL_" + format + ".zip";// 创建最外层文件夹,组装数据成文件夹层级结构File file = new File(filePath);if (!file.exists()) {file.mkdirs();}/*** 处理自己的文件夹结构*/List<EdrmsFileDynamic> list= edrmsArchFileService.select(req.getCategoryId(), conditions);for (EdrmsFileDynamic fileDynamic : list) {// 二级文件夹(以此类推)File file1 = new File(filePath + "/" + fileDynamic.getTitleProper());if (!file1.exists()) {file1.mkdirs();}}FileOutputStream fileOutputStream = null;try {fileOutputStream = new FileOutputStream(new File(zipFilePath));} catch (FileNotFoundException e) {e.printStackTrace();}// 调用工具类压缩文件夹FileUtil.toZip(filePath, fileOutputStream, true);// 调用工具类设置响应格式try {FileUtil.downLoadFile(request, response, zipName, zipFilePath);} catch (UnsupportedEncodingException e) {log.error("用户:{}导出SQL压缩包失败{}", userId, e);throw new RuntimeException("导出失败~");}

FileUtil 工具类中的压缩文件夹方法

/*** 压缩文件夹** @param srcDir 要压缩的文件夹路径* @param out* @param KeepDirStructure true* @throws RuntimeException*/public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {long start = System.currentTimeMillis();ZipOutputStream zos = null;File sourceFile = null;try {zos = new ZipOutputStream(out);sourceFile = new File(srcDir);// 压缩文件夹compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);long end = System.currentTimeMillis();log.info("压缩完成,耗时:{}ms", end - start);} catch (Exception e) {throw new RuntimeException("zip error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();} catch (IOException e) {e.printStackTrace();}}// 删除压缩之前的文件夹if (sourceFile != null) {log.info("正在删除原文件");deleteFolder(sourceFile);}}}

compress方法

private static void compress(File sourceFile, ZipOutputStream zos, String name,boolean KeepDirStructure) throws Exception {byte[] buf = new byte[BUFFER_SIZE];if (sourceFile.isFile()) {// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字zos.putNextEntry(new ZipEntry(name));// copy文件到zip输出流中int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}// Complete the entryzos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0) {// 需要保留原来的文件结构时,需要对空文件夹进行处理if (KeepDirStructure) {// 空文件夹的处理zos.putNextEntry(new ZipEntry(name + "/"));// 没有文件,不需要文件的copyzos.closeEntry();}} else {for (File file : listFiles) {// 判断是否需要保留原来的文件结构if (KeepDirStructure) {// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了compress(file, zos, name + "/" + file.getName(), KeepDirStructure);} else {compress(file, zos, file.getName(), KeepDirStructure);}}}}}

FileUtil 中设置响应格式的方法

/*** 设置导出zip的响应格式** @param request* @param response* @param fileZip zip的名字* @param filePath zip的路径* @throws UnsupportedEncodingException*/public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileZip, String filePath) throws UnsupportedEncodingException {//进行浏览器下载final String userAgent = request.getHeader("USER-AGENT");//判断浏览器代理并分别设置响应给浏览器的编码格式String finalFileName = null;if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {// IE浏览器finalFileName = URLEncoder.encode(fileZip, "UTF8");System.out.println("IE浏览器");} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器finalFileName = new String(fileZip.getBytes(), "ISO8859-1");} else {// 其他浏览器finalFileName = URLEncoder.encode(fileZip, "UTF8");}// 告知浏览器下载文件,而不是直接打开,浏览器默认为打开response.setContentType("application/x-download");// 下载文件的名称response.setHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");ServletOutputStream servletOutputStream = null;try {servletOutputStream = response.getOutputStream();} catch (IOException e) {e.printStackTrace();}DataOutputStream temps = new DataOutputStream(servletOutputStream);// 浏览器下载文件的路径DataInputStream in = null;try {in = new DataInputStream(new FileInputStream(filePath));} catch (FileNotFoundException e) {e.printStackTrace();}byte[] b = new byte[2048];// 之后用来删除临时压缩文件File reportZip = new File(filePath);try {while ((in.read(b)) != -1) {temps.write(b);}temps.flush();} catch (Exception e) {e.printStackTrace();} finally {if (temps != null) {try {temps.close();} catch (IOException e) {e.printStackTrace();}}if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (reportZip != null) {// 删除服务器本地产生的临时压缩文件!reportZip.delete();}try {servletOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。