ABC 等多个系统 每个系统下有多个附件 ,每个系统获取自己最新日期的文档

1.假如有 ABC 等多个系统 每个系统下有多个附件 ,每个系统获取自己最新日期的文档(每个文件都标有最新日期
duptime ) Java代码从表中查询出的 list怎莫处理 得到每个系统下面最新的文件

Map<String, List<Attachment>> attachmentsBySystem = new HashMap<>();

// 对每个附件进行遍历,根据系统将附件分组放入对应的列表中
for (Attachment attachment : attachmentList) {
    String system = attachment.getSystem();
    List<Attachment> attachments = attachmentsBySystem.getOrDefault(system, new ArrayList<>());
    attachments.add(attachment);
    attachmentsBySystem.put(system, attachments);
}

注释解释:

attachmentsBySystem是一个Map<String, List>,用于按系统将附件分组存储。
遍历attachmentList中的每个附件。
获取附件的系统名称。
使用getOrDefault方法从attachmentsBySystem中获取当前系统的附件列表,如果不存在则创建一个新的空列表。
将当前附件添加到系统的附件列表中。
将更新后的附件列表放回attachmentsBySystem中。

Map<String, Attachment> latestAttachmentsBySystem = new HashMap<>();

// 遍历每个系统的附件列表,找到最新日期的附件
for (Map.Entry<String, List<Attachment>> entry : attachmentsBySystem.entrySet()) {
    String system = entry.getKey();
    List<Attachment> attachments = entry.getValue();
    
    if (attachments.isEmpty()) {
        continue;
    }
    
    Attachment latestAttachment = attachments.get(0);
    for (Attachment attachment : attachments) {
        if (attachment.getDuptime().after(latestAttachment.getDuptime())) {
            latestAttachment = attachment;
        }
    }
    
    latestAttachmentsBySystem.put(system, latestAttachment);
}

注释解释:

latestAttachmentsBySystem是一个Map<String, Attachment>,用于存储每个系统的最新附件。
遍历attachmentsBySystem中的每个系统和对应的附件列表。
获取当前系统的名称和附件列表。
如果附件列表为空,则跳过当前系统。
初始化latestAttachment为当前附件列表的第一个附件。
遍历附件列表中的每个附件。
比较附件的duptime属性与当前最新附件的duptime属性,如果后者较晚,则更新latestAttachment为当前附件。
将最新附件添加到latestAttachmentsBySystem中。

2.下载文件建立系统文件夹并把文档放在里面

// 遍历每个系统的最新附件
for (Map.Entry<String, Attachment> entry : latestAttachmentsBySystem.entrySet()) {
    String system = entry.getKey();
    Attachment attachment = entry.getValue();

    // 创建系统文件夹
    File systemFolder = new File("path/to/directory/" + system);
    if (!systemFolder.exists()) {
        systemFolder.mkdirs();
    }

    // 下载文档并保存到系统文件夹中
    String documentUrl = attachment.getDocumentUrl();
    String documentFileName = attachment.getDocumentFileName();
    try (InputStream inputStream = new URL(documentUrl).openStream()) {
        Files.copy(inputStream, Paths.get(systemFolder.getPath(), documentFileName), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这段代码通过遍历每个系统的最新附件,创建系统文件夹,并将附件的文档下载并保存到系统文件夹中。请注意替换代码中的"path/to/directory/"为实际的存储路径

posted @ 2024-01-16 08:40  我的心儿  阅读(19)  评论(0)    收藏  举报