说明
在jdk1.8版本中,已经提供了针对文件压缩zip包的工具类。
1、压缩文件集合到指定目录
/** * @Description 压缩文件集合到指定的目录 **/ public static void zipFiles(String zipFileName, String zipFilePath, List<FileDto> fileList) { logger.info("fileList -- > " + JSON.toJSONString(fileList)); if(CollectionUtils.isEmpty(fileList)){ logger.info("需要压缩的文件为空"); return; } // 临时文件 File tempfile = new File(zipFilePath + File.separator + zipFileName); if(tempfile.exists()){ tempfile.delete(); } final InputStream input = null; ZipOutputStream zipOut = null; try { FileOutputStream fos = new FileOutputStream(tempfile); zipOut = new ZipOutputStream(fos); // zip的名称为 zipOut.setComment(zipFileName); // zipOut.setEncoding("GBK"); fileList.forEach(fileDto -> { byte [] fileBytes = getFileData(fileDto.getFilePath(), fileDto.getFileName()); input = new ByteArrayInputStream(fileBytes); zipOut.putNextEntry(new ZipEntry(fileDto.getFileName())); int temp = 0; while ((temp = input.read()) != -1) { zipOut.write(temp); } }); }catch (IOException e) { e.printStackTrace(); } finally{ try { if (zipOut != null) {zipOut.close();} if (input != null) {input.close();} } catch (IOException e2) { e2.printStackTrace(); } } }
2、解压(暂未提供)
3、zip转byte[]
注:若在压缩zip包的方法体内将zip压缩包转byte[],需要先将ZipOutputStream流关闭。
/** * 文件转byte[] */ public static byte[] fileToBytes(String path) { File file = new File(path); FileInputStream fis; try { fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[(int)file.length()]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); return bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }
4、byte[]转zip
/** * 字节流写入文件 */ public static void bytesToFile(byte[] data, String filePath) { File file = new File(filePath); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } FileOutputStream o = null; try { o = new FileOutputStream(filePath); o.write(data, 0, data.length); o.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != o) { try { o.close(); } catch (IOException e) { e.printStackTrace(); } } } }