-
背景:因为最近在做一个需求,需要根据模板批量生成pdf,并且可以批量压缩pdf为zip格式到前端页面下载,因为项目保密性不方便直接贴代码,写了个测试类;
-
直接上代码;
package org.example; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Mayz * @description * @date 2021-09-16 16:44 */ public class zipUtils { public static void main(String[] args) throws Exception { byte[] bytes = getBytesFromFile(new File("C:\\Users\\mayz1\\Desktop\\99999.pdf")); byte[] bytes1 = getBytesFromFile(new File("C:\\Users\\mayz1\\Desktop\\999999.pdf")); List<byte[]> dataList = new ArrayList<>(); dataList.add(bytes); dataList.add(bytes1); byte[] zip = zip(dataList); //为了方便测试,于是生成了zip文件,但是生产环境中不需要这一步,直接将byte[]放到response返回给前端就可以咯 getFileByBytes(zip, "C:\\Users\\mayz1\\Desktop\\","test.zip"); } public static void getFileByBytes(byte[] bytes, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); // 判断文件目录是否存在 if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + "\\" + fileName); //输出流 fos = new FileOutputStream(file); //缓冲流 bos = new BufferedOutputStream(fos); //将字节数组写出 bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static byte[] getBytesFromFile(File file) throws Exception { InputStream in = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { throw new Exception("文件过大,不能传输"); } byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("不能转换,"); } in.close(); return bytes; } public static byte[] zip(List<byte[]> dataList) { byte[] b = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(bos); for (int i = 0; i < dataList.size(); i++) { ZipEntry entry = new ZipEntry(i+".pdf"); byte[] data = dataList.get(i); //返回条目数据的未压缩大小;如果未知,则返回 -1 entry.setSize(data.length); // 开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处 zip.putNextEntry(entry); //将字节数组写入当前 ZIP 条目数据 zip.write(data); } zip.closeEntry(); zip.close(); b = bos.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } return b; } }
-
运行,生成zip文件,如下所示;
-
finally,bye!!!今天也是没有bug的一天呢!!!嘻嘻!!!
批量zip压缩byte[]
最新推荐文章于 2023-12-02 17:57:21 发布