java批量下载生成zip压缩包

设计思路:

1.本地先创建一个zip文件

2.将批量下载的文件依次放入zip文件中

3.将zip文件返回给前端

//一、本地先生成zip文件

//要批量下载的文件id数组
String[] ids = new String[] {"1","2"}
byte[] buffer = new byte[1024];
//创建zip
String localZipFile = "D:/temp/test.zip" ;
if(!new File(localZipFile).exists()){
 new File(localZipFile).mkdirs();
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(localZipFile));

//依次获取批量下载的文件
for(int i =0; i<ids.length;i++){
    //设置压缩包内的文件的字符编码,不然文件名可能变成乱码(用户为windows系统)
	out.setEncoding("GBK");
    //从数据库中获取文件的路径和文件名,并放入zip文件中
    String fileId = ids[i];
    Map<String,Object> map =exportManagerService.getFjInfo(fileId);
    FileInputStream inStream = new FileInputStream(new File(map.get("path").toString()));
    out.putNextEntry(new ZipEntry(map.get("name").toString()));
    int len;
    //读入需要下载的文件的内容,打包到zip文件  
	while ((len = inStream.read
  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
你可以使用Java提供的ZipOutputStream类来创建一个zip压缩文件,然后将下载文件添加到该压缩文件中。下面是一段示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class DownloadAndZip { public static void main(String[] args) throws Exception { // 下载文件 URL url = new URL("http://example.com/file.txt"); InputStream in = url.openStream(); FileOutputStream fos = new FileOutputStream("file.txt"); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { fos.write(buffer, 0, length); } in.close(); fos.close(); // 创建zip文件并添加下载文件到其中 FileOutputStream fosZip = new FileOutputStream("file.zip"); ZipOutputStream zipOut = new ZipOutputStream(fosZip); File fileToZip = new File("file.txt"); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int lengthZip; while ((lengthZip = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, lengthZip); } fis.close(); zipOut.closeEntry(); zipOut.close(); fosZip.close(); } } ``` 在上面的示例中,我们首先从指定的URL下载文件并保存到本地文件“file.txt”中。接下来,我们创建一个ZipOutputStream对象,并将下载文件添加到其中。最后,我们将ZipOutputStream写入到一个新的文件“file.zip”中,并关闭所有的输入和输出流。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值