java生成压缩文件封装工具方法

有业务场景需要根据一些树状结构, 打包每个节点的文件到一个zip包. 下面使用  org.apache.tools.zip.ZipOutputStream 封装成一个方法.

/**
	 将文件压缩到ZIP输出流
	 * @param dirPath 目录路径
	 * @param file 文件
	 * @param zouts 输出流
	 * @param fileName 要存储的文件名
	 * @param isDirectory 是否是目录
	 */
	public static void zipFilesToZipFile(String dirPath, File file,
										 ZipOutputStream zouts,String fileName,Boolean isDirectory) {
		FileInputStream fin = null;
		ZipEntry entry = null;
		// 创建复制缓冲区
		try {
			byte[] buf = new byte[4096];
			int readByte = 0;
			if (file.isFile()) {
				// 创建一个文件输入流
				fin = new FileInputStream(file);
				// 创建一个ZipEntry
				entry = new ZipEntry(getEntryName(dirPath, fileName));
				// 存储信息到压缩文件
				zouts.putNextEntry(entry);
				// 复制字节到压缩文件
				while ((readByte = fin.read(buf)) != -1) {
					zouts.write(buf, 0, readByte);
				}
				zouts.closeEntry();
				fin.close();
				System.out.println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
			}else if(isDirectory){
				entry = new ZipEntry(getEntryName(dirPath,fileName));
				// 存储信息到压缩文件
				zouts.putNextEntry(entry);
				zouts.closeEntry();
				System.out.println("添加目录 " + file.getName() + " 到zip文件中!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

下面给出使用的代码.

/**
	 * 根据档案管理的节点结构和上传文件生成Zip文件结构
	 * @param zo 流
	 * @param dirPath zip中上一级目录
	 * @param fmsList FileManagers 节点
	 * @param fileInfos 所上传的文件
	 */
	private void fileManagerFileZip(ZipOutputStream zo, String dirPath, List<FileManagersVo> fmsList, List<FileInfo> fileInfos,
									String saveFileRootPath) {
		for (FileManagersVo fms : fmsList) {
			if("-1".equals(fms.getParentId())){
				//根节点
				try {
					zo.putNextEntry(new ZipEntry(fms.getName() + File.separator));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			String fmsName = fms.getName();
			if(StringUtils.isMeaningFul(dirPath)){
				AuditAchieveDocService.zipFilesToZipFile(dirPath,new File(fmsName),zo,fmsName+File.separator,true);// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
			}
			if(fms.getChildren() != null && fms.getChildren().size() > 0){
				if(StringUtils.isMeaningFul(dirPath)){
					fileManagerFileZip(zo,dirPath+File.separator+fmsName,fms.getChildren(),fileInfos,saveFileRootPath);
				}else{
					fileManagerFileZip(zo,fmsName,fms.getChildren(),fileInfos,saveFileRootPath);
				}
			}
			for (FileInfo fileInfo : fileInfos) {
				if(fileInfo.getRefRecordId().equals(fms.getId())){
					String fileName = fileInfo.getName();
					String filePath = fileInfo.getSavePath();
					if(StringUtils.isMeaningFul(dirPath)){
						//写入文件
						AuditAchieveDocService.zipFilesToZipFile(dirPath+File.separator+fmsName,new File
								(saveFileRootPath+File.separator+filePath),zo,fileName,false);
					}
				}
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/87872976
今日推荐