Java压缩多层目录及文件
public static void main(String[] args) throws Exception { // 压缩目录D: mpsmf_storagehistory下的所有内容到D: mpsmf_storageak20211230.zip compress("D:\tmp\smf_storage\history", "D:\tmp\smf_storage\bak20211230.zip"); // 不指定目标路径,默认压缩目录D: mpsmf_storagehistory下的所有内容到D: mpsmf_storagehistory.zip compress("D:\tmp\smf_storage\history", null); } /** * <一句话功能简述> 压缩文件夹内容 * <功能详细描述> * author: zhanggw * 创建时间: 2021/12/30 * @param targetDir 压缩文件夹目录全路径 * @param compressFilePath zip压缩包存储路径,null表示保存在父级目录下,文件名为targetDir的最后名称+".zip" */ public static void compress(String targetDir, String compressFilePath){ try{ File sourceFile = new File(targetDir); if(StringUtils.isBlank(compressFilePath)){ compressFilePath = sourceFile.getParentFile().getAbsolutePath() + File.separator + sourceFile.getName() + ".zip"; } ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(compressFilePath)); compress(sourceFile, sourceFile.getName(), zipOutputStream); zipOutputStream.close(); }catch (Exception e){ logger.error("压缩文件异常!", e); } } /** * <一句话功能简述> 递归压缩zip * <功能详细描述> * author: zhanggw * 创建时间: 2021/12/30 * @param sourceDir 压缩目标目录 * @param zipDirName zip压缩包中当前目录名称 history/fund * @param targetZipOut zip压缩包输出流 */ private static void compress(File sourceDir, String zipDirName, ZipOutputStream targetZipOut){ if(!sourceDir.exists()){ logger.debug("待压缩的目录"+sourceDir.getName()+"不存在"); return; } File[] files = sourceDir.listFiles(); if(files == null || files.length ==0){ return; } FileInputStream fis = null; BufferedInputStream bis = null; byte[] byteArray = new byte[1024*10]; try{ for (File file : files) { if (file.isFile()) { logger.debug("开始压缩:{}", file.getAbsoluteFile()); ZipEntry zipEntry = new ZipEntry(zipDirName + File.separator + file.getName()); targetZipOut.putNextEntry(zipEntry); //读取待压缩的文件并写进压缩包里 fis = new FileInputStream(file); bis = new BufferedInputStream(fis, 1024 * 10); int read; while ((read = bis.read(byteArray, 0, 1024 * 10)) != -1) { targetZipOut.write(byteArray, 0, read); } //如果需要删除源文件,则需要执行下面2句 //fis.close(); //fs[i].delete(); } else if (file.isDirectory()) { logger.debug("进入目录:{}", file.getAbsoluteFile()); compress(file, zipDirName + File.separator + file.getName(), targetZipOut); } }//end for }catch (IOException e) { logger.error("打包异常!",e); } finally{ //关闭流 try { if(null!=bis) bis.close(); if(null!=fis) fis.close(); } catch (IOException e) { logger.error("打包关闭流异常!",e); } } }
上一篇:
Python 安装包管理工具 pip
下一篇:
IDEA如何添加项目启动参数