java 文件 批量下载,多个文件用压缩包实现

/***
	 * obtain outputstream
	 * 
	 * @param uploadifyFile 文件对象
	 * @param out
	 * @throws Exception
	 */
	public void beachDownloadUploadify(List<UploadifyFile> uploadifyFiles, OutputStream out) {
		if (UtilGet.listIsEmpty(uploadifyFiles)) {
			// change UploadifyFile to outputstream 
			Date currentTime = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat(Constants.FORMATNAME);
			Random r = new Random();
			String time =formatter.format(currentTime);
			String tempMulit = Constants.TEMP_DOWNLOAD + time + r.nextDouble()+r.nextLong()+r.nextLong()+r.nextInt();//临时文件目录(做压缩文件用)
			String mulitPath = tempMulit+Constants.ZIPFILE;//压缩文件目录
			File tempDownload = new File(tempMulit);
			if (!tempDownload.exists() || !tempDownload.isDirectory()) {
				tempDownload.mkdirs();
			}
			try {
				File zipFiel = new File(mulitPath);
				ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(zipFiel);
				zipOutput.setEncoding("GBK");
				//将文件写入压缩文件夹
				for (UploadifyFile uploadifyFile : uploadifyFiles) {
					String filePath = Constants.BASEPATH + Constants.SEP + uploadifyFile.getFilePath() + Constants.SEP
							+ uploadifyFile.getRegisterName() + uploadifyFile.getRegisterExt();
					File inputFile = new File(filePath);
					zipOutput.putArchiveEntry(new ZipArchiveEntry(uploadifyFile.getOriginalFileFullName()));
					FileInputStream in = new FileInputStream(inputFile);
					int b;
					while ((b = in.read()) != -1) {
						zipOutput.write(b);
					}
					in.close();
				}
				zipOutput.closeArchiveEntry();
				zipOutput.close();
				if (null != tempDownload && tempDownload.isDirectory()) {
					FileUtils.deleteDirectory(tempDownload);
				}
				File file = new File(mulitPath);
				FileInputStream fis = new FileInputStream(file);
				BufferedInputStream buff = new BufferedInputStream(fis);
				byte[] b = new byte[10240];
				long k = 0;
				while (k < file.length()) {
					int j = buff.read(b, 0, 10240);
					k += j;
					out.write(b, 0, j);
				}
				out.flush();
				if (null != buff) {
					buff.close();
				}
				if (null != out) {
					out.close();
				}
				
				if(null!=zipFiel&&zipFiel.isFile()){
					FileUtils.deleteQuietly(zipFiel);
				}
			} catch (Exception e) {
				log.warn(e);
			}
		}
	}

 

    组装文件对象:

 

	@Override
	@SuppressWarnings("unchecked")
	public void beachFileDownload(String ruleStr, OutputStream out) throws Exception {
		String hqlTemp = StringUtils.replace(ruleStr, ";", "','");
		List<AttachFile> list = (List<AttachFile>) baseManager.getAll(" requireFileCode in ('" + hqlTemp + "') ");
		List<UploadifyFile> uploadifies = new ArrayList<UploadifyFile>();
		if (UtilGet.isCheckList(list)) {
			for (AttachFile attachFile : list) {
				if (null != attachFile) {
					UploadifyFile uploadifyFile = new UploadifyFile();
					uploadifyFile.setFileCode(attachFile.getRequireFileCode());
					uploadifyFile.setRegisterName(StringUtils.substring(attachFile.getPhysicalFile(), 0,
							StringUtils.lastIndexOf(attachFile.getPhysicalFile(), ".")));
					uploadifyFile.setRegisterExt(StringUtils.substring(attachFile.getPhysicalFile(),
							StringUtils.lastIndexOf(attachFile.getPhysicalFile(), ".")));
					uploadifyFile.setFilePath(StringUtils.substring(attachFile.getFileUrl(), 0,
							StringUtils.lastIndexOf(attachFile.getFileUrl(), attachFile.getPhysicalFile()) - 1));
					uploadifyFile.setOriginalFileFullName(attachFile.getFileName());
					uploadifies.add(uploadifyFile);
				}
			}
			DownloadUploadifyUtil downloadUploadifyUtil = new DownloadUploadifyUtil();
			downloadUploadifyUtil.beachDownloadUploadify(uploadifies, out);
		}
	}

 

    controller 层 调用

 

/****
	 * 批量下载
	 * @param attachFileRecord
	 * @param request
	 * @param response
	 */
	@RequestMapping(method =RequestMethod.GET, value = PBDOWNLOAD, params = "method=beathDownload")
	public void beachDownload(AttachFileRecord attachFileRecord, HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter(ID);
		try {
			if (StringUtils.isNotBlank(ids)) {
				int i = StringUtils.split(ids,";").length;
				response.setContentType("text/html; charset=GBK");
				String fileName = DownloadUploadifyUtil.strByteGB("档案库文档["+i+"].zip", request);
				response.setContentType("application/x-msdownload");
				OutputStream out=response.getOutputStream();
				response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
				attachFileService.beachFileDownload(ids,out);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,可以使用Java中的ZipOutputStream实现文件批量下载并合成一个压缩包。 首先,需要创建一个ZipOutputStream对象,用于将文件写入压缩包中。然后,遍历需要下载文件列表,将每个文件逐个添加到压缩包中。 示例代码如下: ```java import java.io.*; import java.util.zip.*; public class FileDownloader { public static void main(String[] args) { // 定义要下载文件列表 String[] filesToDownload = {"file1.txt", "file2.txt", "file3.txt"}; // 定义压缩包文件名 String zipFileName = "download.zip"; try { // 创建压缩包输出流 FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件列表,逐个添加到压缩包中 for (String fileName : filesToDownload) { // 创建文件输入流 FileInputStream fis = new FileInputStream(fileName); // 添加压缩包条目 zos.putNextEntry(new ZipEntry(fileName)); // 将文件内容写入压缩包 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭输入流 fis.close(); // 关闭条目 zos.closeEntry(); } // 关闭压缩包输出流 zos.close(); fos.close(); System.out.println("文件下载成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们定义了要下载文件列表,以及压缩包文件名。然后,创建了一个ZipOutputStream对象,用于将文件写入压缩包中。在遍历文件列表的过程中,我们使用FileInputStream读取文件内容,并使用ZipOutputStream文件内容写入压缩包中。最后,关闭压缩包输出流,完成文件下载压缩包的生成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xxpp688

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值