java工具類實(shí)現(xiàn)文件壓縮zip以及解壓縮功能
對(duì)hutool工具類進(jìn)行的封裝
依賴
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.15</version> <scope>compile</scope> </dependency>
壓縮代碼
package com.myrc.web.util; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ZipUtil; import lombok.extern.slf4j.Slf4j; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.List; /** * 自定義 (zip壓縮包/文件) 操作工具類 * * @author gjq * @date 2023/2/16 */ @Slf4j @SuppressWarnings("all") public class ZipFileUtils { /** * * 生成Zip壓縮包 (注意是對(duì)hutool的二次封裝,所以必須要有hutool依賴) * * @param targetZipFile 要生成的目標(biāo)zip壓縮包 * @param sourceFiles 壓縮包中包含的文件集合 * @param dirWithFlag 是否將文件目錄一同打包進(jìn)去 (true:壓縮包中包含文件目錄,false:壓縮包中不包含目錄) * @author liukai */ public static void generateZip(File targetZipFile, List<File> sourceFiles, boolean dirWithFlag) { if (CollUtil.isNotEmpty(sourceFiles)) { File[] fileArr = sourceFiles.toArray(new File[]{}); ZipUtil.zip(targetZipFile, dirWithFlag, fileArr); } } /** * 下載ZIP壓縮包(會(huì)對(duì)下載后的壓縮包進(jìn)行刪除) * * @param file zip壓縮包文件 * @param response 響應(yīng) * @author liukai */ public static void downloadZip(File file, HttpServletResponse response) { OutputStream toClient = null; try { // 以流的形式下載文件。 BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); toClient = new BufferedOutputStream(response.getOutputStream()); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); toClient.write(buffer); toClient.flush(); } catch (Exception e) { log.error("下載zip壓縮包過(guò)程發(fā)生異常:", e); } finally { if (toClient != null) { try { toClient.close(); } catch (IOException e) { log.error("zip包下載關(guān)流失敗:", e); } } //刪除改臨時(shí)zip包(此zip包任何時(shí)候都不需要保留,因?yàn)樵次募S時(shí)可以再次進(jìn)行壓縮生成zip包) file.delete(); } } /** * 任何單文件下載 * * @param file 要下載的文件 * @param response 響應(yīng) * @author liukai */ public static void downloadAnyFile(File file, HttpServletResponse response) { FileInputStream fileInputStream = null; OutputStream outputStream = null; try { fileInputStream = new FileInputStream(file); // 清空response response.reset(); //防止文件名中文亂碼 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8")); //根據(jù)文件動(dòng)態(tài)setContentType response.setContentType(new MimetypesFileTypeMap().getContentType(file) + ";charset=UTF-8"); outputStream = response.getOutputStream(); byte[] bytes = new byte[2048]; int len; while ((len = fileInputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }
FileUtil 工具類補(bǔ)齊
public class FileUtil { /** * 獲取指定文件夾下所有文件,不含文件夾里的文件 * * @param dirFilePath 文件夾路徑 * @return */ public static List<File> getAllFile(String dirFilePath) { if (StrUtil.isBlank(dirFilePath)) return null; return getAllFile(new File(dirFilePath)); } /** * 獲取指定文件夾下所有文件,不含文件夾里的文件 * * @param dirFile 文件夾 * @return */ public static List<File> getAllFile(File dirFile) { // 如果文件夾不存在或著不是文件夾,則返回 null if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile()) return null; File[] childrenFiles = dirFile.listFiles(); if (Objects.isNull(childrenFiles) || childrenFiles.length == 0) return null; List<File> files = new ArrayList<>(); for (File childFile : childrenFiles) { // 如果是文件,直接添加到結(jié)果集合 if (childFile.isFile()) { files.add(childFile); } //以下幾行代碼取消注釋后可以將所有子文件夾里的文件也獲取到列表里 // else { // // 如果是文件夾,則將其內(nèi)部文件添加進(jìn)結(jié)果集合 // List<File> cFiles = getAllFile(childFile); // if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue; // files.addAll(cFiles); // } } return files; } }
解壓縮
zipUtil是hutool包下的工具類
File unzip = ZipUtil.unzip(zipPath, StandardCharsets.UTF_8);
使用:
//獲取該目錄下全部的文件 List<File> allFile = FileUtil.getAllFile(configPath); //對(duì)目標(biāo)文件集 壓縮 ZipFileUtils.generateZip(new File(zipPath),allFile,true);
附:Java hutool 實(shí)現(xiàn)多個(gè)文件壓縮成壓縮包并下載至本地
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>xxx</version> </dependency>
List<ReqDocZip> reqDocZips = dealWithOutPutItems(retPageDocFiles); String[] fileNames = reqDocZips.stream().map(ReqDocZip::getName).toArray(String[]::new); for (ReqDocZip reqDocZip : reqDocZips) { if (reqDocZip.getName().equals(fileName)) { //導(dǎo)出同名文件會(huì)異常,拼接一個(gè)隨機(jī)字符串 fileName = UUID.randomUUID() + "-" + fileName; break; } } ByteArrayInputStream[] inputStreams = reqDocZips.stream().map(ReqDocZip::getInputStream).toArray(ByteArrayInputStream[]::new); response.setContentType("application/zip"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("導(dǎo)出歸檔文檔", StandardCharsets.UTF_8.toString()) + ".zip"); ZipUtil.zip(response.getOutputStream(), fileNames, inputStreams);
@Getter @Setter public class ReqDocZip { private String name; private InputStream inputStream; }
總結(jié)
到此這篇關(guān)于java工具類實(shí)現(xiàn)文件壓縮zip以及解壓縮功能的文章就介紹到這了,更多相關(guān)java文件壓縮zip及解壓縮內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring使用OXM進(jìn)行對(duì)象XML映射解析
這篇文章主要介紹了spring使用OXM進(jìn)行對(duì)象XML映射解析,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12Java中的Set、List、Map的用法與區(qū)別介紹
這篇文章主要介紹了Java中的Set、List、Map的用法與區(qū)別,需要的朋友可以參考下2016-06-06Java項(xiàng)目導(dǎo)入IDEA的流程配置以及常見(jiàn)問(wèn)題解決方法
通常一個(gè)團(tuán)隊(duì)中可能有人用eclipse,有人用intelliJ,那么經(jīng)常會(huì)出現(xiàn)需要導(dǎo)入別人用eclipse建好的web項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Java項(xiàng)目導(dǎo)入IDEA的流程配置以及常見(jiàn)問(wèn)題解決方法的相關(guān)資料,需要的朋友可以參考下2023-05-05Java tomcat手動(dòng)配置servlet詳解
這篇文章主要為大家介紹了tomcat手動(dòng)配置servlet,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2021-11-11spring profile 多環(huán)境配置管理詳解
這篇文章主要介紹了 spring profile 多環(huán)境配置管理詳解的相關(guān)資料,需要的朋友可以參考下2017-01-01Spring?Boot?+?EasyExcel?+?SqlServer?進(jìn)行批量處理數(shù)據(jù)的高效方法
在日常開(kāi)發(fā)和工作中,我們可能要根據(jù)用戶上傳的文件做一系列的處理,本篇文章就以Excel表格文件為例,主要介紹了Spring?Boot?+?EasyExcel?+?SqlServer?進(jìn)行批量處理數(shù)據(jù)的高效方法,需要的朋友可以參考下2024-06-06java中的Serializable、transient關(guān)鍵字詳解
這篇文章主要介紹了java中的Serializable、transient關(guān)鍵字詳解,序列化只會(huì)保存屬性值,不會(huì)保存方法,通過(guò)反序列化可以把序列化后的內(nèi)容恢復(fù)成對(duì)象,需要的朋友可以參考下2023-09-09Java中的關(guān)鍵字_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
關(guān)鍵字也稱為保留字,是指Java語(yǔ)言中規(guī)定了特定含義的標(biāo)示符。對(duì)于保留字,用戶只能按照系統(tǒng)規(guī)定的方式使用,不能自行定義2017-04-04java 直接調(diào)用python腳本,并傳遞參數(shù)代碼實(shí)例
這篇文章主要介紹了java調(diào)用python腳本傳遞參數(shù)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04