java 批量下载文件(开发笔记)

需求:

 下载文件,选择单个文档则下载单个文档,选择多个文档则讲多个文档压缩进一个压缩文件。

 

	public ResponseEntity<InputStreamResource> downloadFiles(String literIds,String type) throws YMLibWebApplicationException {
		Assert.notNull(literIds, "未指定要下载的文献");
		if(null==type){
			type="";
		}
		String[] ids = literIds.split(",");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		QFullTextLibrary qfullTextLibrary = QFullTextLibrary.fullTextLibrary;
		Predicate predicate = qfullTextLibrary.id.in(ids);
		Iterable<FullTextLibrary> iter = fullTextLibraryRepository.findAll(predicate);
		int total = 0;
		String fileName = "";
		Collection<String> fileIds = new ArrayList<String>();
	
		for (FullTextLibrary one : iter) {
			
			String fileId = one.getFileId();
			if (fileId != null && !fileId.equals("")) {
							
				fileIds.add(fileId);
				
				total++;
			}
			
			
		}
		if (total > 1) {
			fileName = DateUtils.date2String("yyyymmdd") + ".zip";
		}
		headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName));
		long length = 0L;

		Criteria cr = Criteria.where("_id").in(fileIds);
		Query query = new Query(cr);
		List<GridFSDBFile> files = gridFsOps.find(query);
		if (!files.isEmpty()) {
			if (files.size() == 1) {
				GridFSDBFile file = files.get(0);
				length = file.getLength();
				return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
						.cacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS)).headers(headers)
						.body(new InputStreamResource(file.getInputStream()));

			} else {
					long statr_time=System.currentTimeMillis();
				try {
					String zipfilePath = zipFilePath + fileName;
					FileOutputStream outputStream = new FileOutputStream(zipfilePath);
					ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
					// zipOut.putNextEntry(new ZipEntry("/"));
					for (GridFSDBFile file : files) {
						length += file.getLength();
						InputStream in = file.getInputStream();
						String file_id=file.getId().toString();
						zipOut.putNextEntry(new ZipEntry(file.getName()));
						int j = 0;
						byte[] buffer = new byte[1024*1024];
						while ((j = in.read(buffer)) > 0) {
							zipOut.write(buffer, 0, j);
						}
						// 关闭输入流
						in.close();
					}
					zipOut.closeEntry();
					zipOut.flush();
					zipOut.close();
					// 文件压缩成功
					FileInputStream inputStream = new FileInputStream(zipfilePath);
					
					long end_time=System.currentTimeMillis();
					System.out.println(end_time-statr_time);
					return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
							.headers(headers)
							.body(new InputStreamResource(inputStream));

				} catch (Exception e) {
					log.error("压缩文件出错", e);
				}
			}
		}

		return null;

	}

 

文件通过mongoid 去mongofs里面拿,拿出来后判断文件的个数,多个文件则进行压缩。代码如上图。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
您可以使用Java的`java.util.zip`包来实现批量下载文件并打包成一个压缩文件。下面是一个简单的示例代码: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileDownloader { public static void main(String[] args) { String[] fileUrls = { "http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt" }; String outputZipFile = "output.zip"; try { // 创建输出流,用于写入压缩文件 FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件URL列表,逐个下载文件并写入压缩文件 for (String fileUrl : fileUrls) { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); InputStream is = new BufferedInputStream(new URL(fileUrl).openStream()); ZipEntry entry = new ZipEntry(fileName); zos.putNextEntry(entry); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); System.out.println("文件下载并打包完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例中,您需要将`fileUrls`数组替换为您要下载文件URL列表,将`outputZipFile`字符串替换为您想要生成的压缩文件文件名。该代码会逐个下载文件并将其写入压缩文件中。最后,您可以在控制台输出中看到提示,确认下载和打包过程已完成。 请注意,此示例仅仅是一个简单的实现,您可能需要根据您的具体需求进行适当的修改和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值