• Java代码如何对Excel文件进行zip压缩


    1:新建 ZipUtils 工具类

    1. package com.ly.cloud.datacollection.util;
    2. import java.io.File;
    3. import java.io.FileInputStream;
    4. import java.io.FileOutputStream;
    5. import java.io.IOException;
    6. import java.io.OutputStream;
    7. import java.net.URLEncoder;
    8. import java.nio.ByteBuffer;
    9. import java.nio.channels.Channels;
    10. import java.nio.channels.FileChannel;
    11. import java.nio.channels.WritableByteChannel;
    12. import java.util.ArrayList;
    13. import java.util.List;
    14. import java.util.zip.ZipEntry;
    15. import java.util.zip.ZipOutputStream;
    16. import javax.servlet.http.HttpServletResponse;
    17. import lombok.extern.slf4j.Slf4j;
    18. @Slf4j
    19. public class ZipUtils {
    20. private static final int BUFFER_SIZE = 10 * 1024;
    21. /**
    22. *
    23. * @param fileList 多文件列表
    24. * @param zipPath 压缩文件临时目录
    25. * @return
    26. */
    27. public static Boolean zipFiles(List fileList, File zipPath) {
    28. boolean flag = true;
    29. // 1 文件压缩
    30. if (!zipPath.exists()) { // 判断压缩后的文件存在不,不存在则创建
    31. try {
    32. zipPath.createNewFile();
    33. } catch (IOException e) {
    34. flag=false;
    35. e.printStackTrace();
    36. }
    37. }
    38. FileOutputStream fileOutputStream=null;
    39. ZipOutputStream zipOutputStream=null;
    40. FileInputStream fileInputStream=null;
    41. try {
    42. fileOutputStream=new FileOutputStream(zipPath); // 实例化 FileOutputStream对象
    43. zipOutputStream=new ZipOutputStream(fileOutputStream); // 实例化 ZipOutputStream对象
    44. ZipEntry zipEntry=null; // 创建 ZipEntry对象
    45. for (int i=0; i// 遍历源文件数组
    46. fileInputStream = new FileInputStream(fileList.get(i)); // 将源文件数组中的当前文件读入FileInputStream流中
    47. zipEntry = new ZipEntry("("+i+")"+fileList.get(i).getName()); // 实例化ZipEntry对象,源文件数组中的当前文件
    48. zipOutputStream.putNextEntry(zipEntry);
    49. int len; // 该变量记录每次真正读的字节个数
    50. byte[] buffer=new byte[BUFFER_SIZE]; // 定义每次读取的字节数组
    51. while ((len=fileInputStream.read(buffer)) != -1) {
    52. zipOutputStream.write(buffer, 0, len);
    53. }
    54. }
    55. zipOutputStream.closeEntry();
    56. zipOutputStream.close();
    57. fileInputStream.close();
    58. fileOutputStream.close();
    59. } catch (IOException e) {
    60. flag=false;
    61. e.printStackTrace();
    62. } finally {
    63. try {
    64. fileInputStream.close();
    65. zipOutputStream.close();
    66. fileOutputStream.close();
    67. } catch (Exception e){
    68. flag=false;
    69. e.printStackTrace();
    70. }
    71. }
    72. return flag;
    73. }
    74. /**
    75. * @param srcDir 压缩文件夹路径
    76. * @param keepDirStructure 是否保留原来的目录结构,
    77. * true:保留目录结构;
    78. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
    79. * @param response
    80. * @throws RuntimeException 压缩失败会抛出运行时异常
    81. */
    82. public static void toZip(String[] srcDir, String outDir,
    83. boolean keepDirStructure, HttpServletResponse response) throws RuntimeException, Exception {
    84. // 设置输出的格式
    85. response.reset();
    86. response.setContentType("bin");
    87. outDir = URLEncoder.encode(outDir,"UTF-8");
    88. response.addHeader("Content-Disposition","attachment;filename=" + outDir);
    89. OutputStream out = response.getOutputStream();
    90. response.setContentType("application/octet-stream");
    91. ZipOutputStream zos = null;
    92. try {
    93. zos = new ZipOutputStream(out);
    94. List sourceFileList = new ArrayList();
    95. for (String dir : srcDir) {
    96. File sourceFile = new File(dir);
    97. sourceFileList.add(sourceFile);
    98. }
    99. compress(sourceFileList, zos, keepDirStructure);
    100. } catch (Exception e) {
    101. throw new RuntimeException("zip error from ZipUtils", e);
    102. }
    103. finally {
    104. if (zos != null) {
    105. try {
    106. zos.close();
    107. out.close();
    108. } catch (IOException e) {
    109. e.printStackTrace();
    110. }
    111. }
    112. }
    113. }
    114. /**
    115. * @param srcDir 压缩文件夹路径
    116. * @param keepDirStructure 是否保留原来的目录结构,
    117. * true:保留目录结构;
    118. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
    119. * @param response
    120. * @throws RuntimeException 压缩失败会抛出运行时异常
    121. */
    122. public static void toZip(String[] srcDir, String outDir,
    123. boolean keepDirStructure) throws RuntimeException, Exception {
    124. // 设置输出的格式
    125. //outDir = URLEncoder.encode(outDir,"UTF-8");
    126. long start= System.currentTimeMillis();
    127. FileOutputStream out=null;
    128. ZipOutputStream zos = null;
    129. try {
    130. out=new FileOutputStream(outDir); // 实例化 FileOutputStream对象
    131. zos = new ZipOutputStream(out);
    132. List sourceFileList = new ArrayList();
    133. for (String dir : srcDir) {
    134. File sourceFile = new File(dir);
    135. sourceFileList.add(sourceFile);
    136. }
    137. compress(sourceFileList, zos, keepDirStructure);
    138. } catch (Exception e) {
    139. throw new RuntimeException("zip error from ZipUtils", e);
    140. }
    141. finally {
    142. if (zos != null) {
    143. try {
    144. zos.close();
    145. out.close();
    146. log.info(outDir+"压缩完成");
    147. printInfo(start);
    148. } catch (IOException e) {
    149. e.printStackTrace();
    150. }
    151. }
    152. }
    153. }
    154. /**
    155. * 递归压缩方法
    156. *
    157. * @param sourceFile 源文件
    158. * @param zos zip输出流
    159. * @param name 压缩后的名称
    160. * @param keepDirStructure 是否保留原来的目录结构,
    161. * true:保留目录结构;
    162. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
    163. * @throws Exception 异常
    164. */
    165. private static void compress(File sourceFile, ZipOutputStream zos,
    166. String name, boolean keepDirStructure) throws Exception {
    167. byte[] buf = new byte[BUFFER_SIZE];
    168. recursion(sourceFile, zos, name, keepDirStructure, buf);
    169. }
    170. /**
    171. *
    172. * @param sourceFileList 源文件列表
    173. * @param zos zip输出流
    174. * @param keepDirStructure 是否保留原来的目录结构,
    175. * true:保留目录结构;
    176. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
    177. * @throws Exception 异常
    178. */
    179. private static void compress(List sourceFileList,
    180. ZipOutputStream zos, boolean keepDirStructure) throws Exception {
    181. byte[] buf = new byte[BUFFER_SIZE];
    182. for (File sourceFile : sourceFileList) {
    183. String name = sourceFile.getName();
    184. recursion(sourceFile, zos, name, keepDirStructure, buf);
    185. }
    186. }
    187. /**
    188. *
    189. * @param sourceFile 源文件
    190. * @param zos zip输出流
    191. * @param name 文件名
    192. * @param keepDirStructure 否保留原来的目录结构,
    193. * true:保留目录结构;
    194. * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
    195. * @param buf 字节数组
    196. * @throws Exception 异常
    197. */
    198. private static void recursion(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure, byte[] buf) {
    199. if (sourceFile.isFile()) {
    200. FileInputStream in=null;
    201. try {
    202. in = new FileInputStream(sourceFile);
    203. zos.putNextEntry(new ZipEntry(name));
    204. int len;
    205. while ((len = in.read(buf)) != -1) {
    206. zos.write(buf, 0, len);
    207. }
    208. zos.closeEntry();
    209. in.close();
    210. } catch (IOException e) {
    211. e.printStackTrace();
    212. }finally {
    213. try {
    214. in.close();
    215. } catch (IOException e) {
    216. e.printStackTrace();
    217. }
    218. }
    219. } else {
    220. File[] listFiles = sourceFile.listFiles();
    221. if (listFiles == null || listFiles.length == 0) {
    222. if (keepDirStructure) {
    223. try {
    224. zos.putNextEntry(new ZipEntry(name + "/"));
    225. zos.closeEntry();
    226. } catch (IOException e) {
    227. e.printStackTrace();
    228. }
    229. }
    230. } else {
    231. for (File file : listFiles) {
    232. if (keepDirStructure) {
    233. try {
    234. compress(file, zos, name + "/" + file.getName(),
    235. true);
    236. } catch (Exception e) {
    237. e.printStackTrace();
    238. }
    239. } else {
    240. try {
    241. compress(file, zos, file.getName(), false);
    242. } catch (Exception e) {
    243. e.printStackTrace();
    244. }
    245. }
    246. }
    247. }
    248. }
    249. }
    250. public static int deleteFile(File file) {
    251. //判断是否存在此文件
    252. int count=0;
    253. if (file.exists()) {
    254. //判断是否是文件夹
    255. if (file.isDirectory()) {
    256. File[] files = file.listFiles();
    257. //判断文件夹里是否有文件
    258. if (files.length >= 1) {
    259. //遍历文件夹里所有子文件
    260. for (File file1 : files) {
    261. //是文件,直接删除
    262. if (file1.isFile()) {
    263. count++;
    264. file1.delete();
    265. } else {
    266. //是文件夹,递归
    267. count++;
    268. deleteFile(file1);
    269. }
    270. }
    271. //file此时已经是空文件夹
    272. file.delete();
    273. } else {
    274. //是空文件夹,直接删除
    275. file.delete();
    276. }
    277. } else {
    278. //是文件,直接删除
    279. file.delete();
    280. }
    281. } else {
    282. }
    283. return count;
    284. }
    285. public static void downloadFile(String path, File file, String outDir, HttpServletResponse response){
    286. OutputStream os = null;
    287. FileInputStream fis=null;
    288. try {
    289. fis = new FileInputStream(file);
    290. // 取得输出流
    291. os = response.getOutputStream();
    292. //String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
    293. outDir = URLEncoder.encode(outDir,"UTF-8");
    294. response.addHeader("Content-Disposition","attachment;filename=" + outDir);
    295. response.setContentType("application/octet-stream");
    296. response.setHeader("Content-Length", String.valueOf(file.length()));
    297. //response.setHeader("Content-Disposition", "attachment;filename="+ outDir);
    298. //response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
    299. /*
    300. * int len; // 该变量记录每次真正读的字节个数 byte[] buffer=new byte[BUFFER_SIZE]; //
    301. * 定义每次读取的字节数组 while ((len=fis.read(buffer)) != -1) { os.write(buffer, 0, len);
    302. * }
    303. */
    304. WritableByteChannel writableByteChannel = Channels.newChannel(os);
    305. FileChannel fileChannel = fis.getChannel();
    306. ByteBuffer buffer=ByteBuffer.allocate(BUFFER_SIZE);
    307. long total=0L;
    308. int len=0;
    309. while((len=fileChannel.read(buffer))!=-1){
    310. total=total+len;
    311. buffer.flip();
    312. // 保证缓冲区的数据全部写入
    313. while (buffer.hasRemaining())
    314. {
    315. writableByteChannel.write(buffer);
    316. }
    317. buffer.clear();
    318. }
    319. log.info(outDir+"下载完成");
    320. os.flush();
    321. fileChannel.close();
    322. writableByteChannel.close();
    323. } catch (IOException e) {
    324. e.printStackTrace();
    325. }
    326. //文件的关闭放在finally中
    327. finally {
    328. try {
    329. if (fis != null) {
    330. fis.close();
    331. }
    332. if (os != null) {
    333. os.flush();
    334. os.close();
    335. }
    336. } catch (IOException e) {
    337. e.printStackTrace();
    338. }
    339. }
    340. }
    341. public static void printInfo(long beginTime) {
    342. long endTime = System.currentTimeMillis();
    343. long total = endTime - beginTime;
    344. log.info("压缩耗时:" + total / 1000 + "秒");
    345. }
    346. }

    2:简单测试

    1. @GetMapping(value = "/zip")
    2. @AnonymityAnnotation(access = true)
    3. public WebResponse zip(@RequestParam("file") MultipartFile file) throws IOException {
    4. InputStream stream = file.getInputStream();
    5. System.out.println(stream);
    6. //下载压缩后的地址
    7. String path = "D:/91-69ddf076d28040d29e59aec22b65b150";
    8. //获取文件原本的名称
    9. String fileName = file.getOriginalFilename();
    10. System.out.println(fileName);
    11. String[] src = { path + "/" + fileName };
    12. String outDir = path + "/69.zip";
    13. try {
    14. ZipUtils.toZip(src, outDir, true);
    15. } catch (Exception e) {
    16. }
    17. return new WebResponse().success("OK");
    18. }

    3:效果图

  • 相关阅读:
    竞赛 深度学习 opencv python 公式识别(图像识别 机器视觉)
    杰理之上电池工位容易 出现不开机【篇】
    如何降级node 版本
    1.2 课程架构介绍:STM32H5 芯片生命周期管理与安全调试
    8.14 PowerBI系列之DAX函数专题-分析客户购买行为
    java毕业设计城市猎人户外军品店Mybatis+系统+数据库+调试部署
    Java基础:Java类与对象
    spring boot集成redis
    【Python数据科学快速入门系列 | 06】Matplotlib数据可视化基础入门(一)
    Maven 如何配置推送的仓库
  • 原文地址:https://blog.csdn.net/XikYu/article/details/134271821