【四二学堂】java批量打包下载文件zip格式

tech2026-06-15  1

pom文件,注意导包

<dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.9.7</version> </dependency>

下载文件使用实体类

@Data @NoArgsConstructor @AllArgsConstructor public class DownloadVO { private String picPath; private String picName; }

文件工具类

public class FileUtils { /** * list 文件信息列表 * dirPath 文件夹路径 * strZipPath zip生成路径 * fileSysPath 返回zip所在路径 */ public static String batchDownLoadFile(List<DownloadVO> list, String dirPath, String strZipPath, String fileSysPath){ byte[] buffer = new byte[1024]; Date date = new Date(); //生成zip文件存放位置 strZipPath File file = new File(dirPath); if (!file.isDirectory() && !file.exists()) { file.mkdirs(); } try { String fileAllName = dirPath + "/" + strZipPath; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(fileAllName)); //必须设置编码格式。否则,中文会出现乱码。注意:如果该处报错,则是你导包有问题。应该是 org.apache.tools.zip.*里面的包。而不是util包 out.setEncoding("gbk"); // 需要同时下载的多个文件 for (int i = 0; i < list.size(); i++) { DownloadVO download = list.get(i); String fileName = download.getPicName(); String pathname = fileSysPath + "/" + download.getPicPath(); File f = new File(pathname); FileInputStream fis = new FileInputStream(f); out.putNextEntry(new ZipEntry(fileName)); int len; // 读入需要下载的文件的内容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); fis.close(); } out.close(); String fileSysPathTemp = fileAllName.replace(fileSysPath, ""); return fileSysPathTemp; } catch (Exception e) { e.printStackTrace(); System.out.println("文件下载错误"); } return null; } }

使用方法

List<DownloadVO> picList = Lists.newArrayList(); DownloadVO vo1 = new DownloadVO(); vo1.setPicName("1.jpg"); vo1.setPicPath("files/20200706/androidPic_1594010746433.jpg"); picList.add(vo1); DownloadVO vo2 = new DownloadVO(); vo2.setPicName("2"); vo2.setPicPath("files/20200706/androidPic_1594010759792.jpg"); picList.add(vo2); DownloadVO vo3 = new DownloadVO(); vo3.setPicName("3.jpg"); vo3.setPicPath("files/20200706/androidPic_1594010795411.jpg"); picList.add(vo3); String filePath =upLoadPath + "/files/downloadzip/"; String date = DateUtils.getCurrentDateStr("yyyyMMddHHmmss"); String filename = date + ".zip"; String fileSysPath =upLoadPath; String zipPath = FileUtils.batchDownLoadFile(picList, filePath, filename,fileSysPath);

 

 

最新回复(0)