等待文件附件下载完成

Wait for completion of file attachment download

我尝试使用官方 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();
}

我已经尝试在 .exceptionally(...) 之后添加 .complete(Void) 并在 .downloadToFile(File) 之后添加 .complete(File)。 None 其中有效。

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

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

Message.Attachment#downloadToFile()returns一个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;
                         });