首页 > 解决方案 > 等待文件附件下载完成

问题描述

我尝试使用官方 JDA 文档给出的示例代码的变体来下载文件附件。之后,下载的文件应该移动到另一个地方。

List<Message.Attachment> attachments = null;
try {
   attachments = event.getMessage().getAttachments();
} catch (UnsupportedOperationException ignore) {}

File downloadFile;
if (attachments != null && !attachments.isEmpty()) {
   Message.Attachment attachment = attachments.get(0);
   downloadFile = new File("./tmp/testfile");
   downloadFile.getParentFile().mkdirs();
   attachment.downloadToFile(downloadFile)
             .thenAccept(file -> System.out.println("Saved attachment"))
             .exceptionally(t -> {
                                     t.printStackTrace();
                                     return null;
                                 });
}

...

File renamedFile = new File("./files/movedfiled");
renamedFile.getParentFile().mkdirs();
try {
   Files.move(downloadFile.toPath(), renamedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
   e.printStackTrace();
}

我已经尝试添加.complete(Void)after.exceptionally(...).complete(File)after .downloadToFile(File)。这些都不起作用。

大多数情况下,移动文件的大小为 0 字节或根本不存在,而原始文件仍存在于旧目录中(有时下载的文件大小也为 0 字节)。

有没有办法在写入后等待下载完成并关闭以防止移动时文件损坏或者是我的文件系统引起的问题(我使用的是 aarch64 GNU/Linux 系统)?

标签: javadiscord-jda

解决方案


Message.Attachment#downloadToFile()返回一个CompletableFuture。您可以使用CompletableFuture#join()它来等待它完成,但 IIRC 这是一个阻塞操作。更好地使用CompletableFuture#thenAccept()CompletableFuture#thenCompose().

attachment.downloadToFile(downloadFile)
              .thenAccept(file -> {
              // Here goes the code which decides what to do after downloading the file
                         })
              .exceptionally(e -> {
                                e.printStackTrace();
                                return null;
                         });

推荐阅读