java-批量下载文件,并且为每个文件创建文件夹,最后合并成一个压缩包

前言

通过文件url批量下载文件,并且每一个文件创建一个文件夹,以此分类,最后统一打成一个压缩包


一、代码示例

    public void download(List<DownloadContractFileDTO> list) {
       File templateFile = FileUtils.createTemplateFile("zip");
        // 创建一个临时目录用于保存文件夹和文件
        Path tempDir = null;
        try {
            tempDir = Files.createTempDirectory("tempDir");
            for (DownloadContractFileDTO downloadContractFile : list) {
                String name = downloadContractFile.getContractName();
                String code = downloadContractFile.getContractCode();
                List<String> urlList = downloadContractFile.getContractFileUrl();
                // 创建以keyName为名称的文件夹
                String fileName = FileUtil.getFileSubstring(name);
                Path folderPath = Files.createDirectory(tempDir.resolve(fileName + "_" + code));
                for (String url : urlList) {
                    // 下载PDF文件并保存到文件夹中
                    FileUtil.downloadFile(url, folderPath.resolve(name).toString());
                }

            }
            // 压缩文件夹
            FileUtil.zipDirectory(tempDir.toString(),templateFile);
            log.info("文件下载、压缩!完成");
        } catch (Exception e) {
            AssertUtil.notNull(true, "下载失败");
            log.error("下载失败==={}", e.getMessage());
        } finally {
            if (tempDir != null) {
                FileUtil.deleteFilesInDirectory(tempDir.toFile());
            }
            log.info("文件删除完成!");
        }
    }

文件工具类

@Slf4j
public class FileUtil {

    /**
     * 下载文件
     *
     * @param url      url
     * @param filePath filePath
     * @throws IOException
     */
    public static void downloadFile(String url, String filePath) throws IOException {
        try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
             FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param sourceDir   文件
     * @param targetFile 文件
     * @throws IOException
     */
    public static void zipDirectory(String sourceDir, File targetFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(targetFile);
             ZipOutputStream zos = new ZipOutputStream(fos);
             Stream<Path> paths = Files.walk(Paths.get(sourceDir))) {
            paths.filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        try {
                            Path relativePath = Paths.get(sourceDir).relativize(path);
                            ZipEntry zipEntry = new ZipEntry(relativePath.toString());
                            zos.putNextEntry(zipEntry);
                            byte[] buffer = new byte[1024];
                            int length;
                            try (InputStream is = Files.newInputStream(path)) {
                                while ((length = is.read(buffer)) > 0) {
                                    zos.write(buffer, 0, length);
                                }
                            }
                            zos.closeEntry();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        }
    }

    /**
     * @param directory      文件
     */
    public static void deleteFilesInDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteFilesInDirectory(file);
                } else {
                    boolean delete = file.delete();
                    log.info("====delete_file=={},==file=={}", delete, JsonUtils.writeAsJson(file));
                }
            }
        }
        boolean delete = directory.delete();
        log.info("===delete_file=={},==file=={}", delete, JsonUtils.writeAsJson(directory));
    }

    /**
     * 获取文件夹名称
     *
     * @return
     */
    public static String getFileSubstring(String name) {
        if (StringUtils.isBlank(name)) {
            return String.valueOf(System.currentTimeMillis());
        }
        int lastDotIndex = name.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return name.substring(0, lastDotIndex);
        } else {
            return name;
        }
    }
    
    /**
     * 创建临时文件
     */
    public static File createTemplateFile(String fileType) {
        String s = UUID.randomUUID() + "." + fileType;
        String filepath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + File.separator + "temp";
        File dir = new File(filepath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return createSubFile(dir, s);
    }

    /**
     * 创建子文件
     *
     * @param parentDir 父文件夹
     * @param filename  子文件名
     */
    public static File createSubFile(File parentDir, String filename) {
        return new File(parentDir.getAbsolutePath() + File.separator + filename);
    }
}

实体Bean

@Data
@AllArgsConstructor
@NoArgsConstructor
public class DownloadContractFileDTO implements Serializable {

    /**
     * 合同code
     */
    private String contractCode;

    /**
     * 合同名称
     */
    private String contractName;

    /**
     * 合同问 url
     */
    private List<String> contractFileUrl;

}```

# 二、最后效果

![在这里插入图片描述](https://img-blog.csdnimg.cn/ffccf00753004ae0a5dced3ec62e89ce.png#pic_center)


---

# 总结
提示:具体根据自己需求修改代码
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,可以使用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将文件内容写入压缩包中。最后,关闭压缩包输出流,完文件下载压缩包的生
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值