java - 等待文件附件下载完成
问题描述
我尝试使用官方 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 系统)?
解决方案
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;
});
推荐阅读
- python - Discord.py - 对 .event on_message 应用冷却时间
- firebase - Flutter Firebase:如何根据 Firebase 的数据更改前导颜色 ini 颤振?
- python - scipy 的线性约束问题。人口的所有要素都被拒绝
- android - 为什么 AdMob 会限制我的广告,尽管始终使用测试广告并且从不点击我自己的广告?
- r - 如何使用 kbl 格式 =“markdown”指定 kableExtra 选项?
- reactjs - 递增和递减反应钩子
- c# - 映射非简单类型的属性时忽略 AutoMapper UseDestinationValue
- macos - 如何修复 Mac Big Sur 中的“brew cleanup”?
- cmake - 致命错误:libusb/libusb.h:没有为 GNU 无线电安装这样的文件或目录 librtlsdr
- excel - 如何在 Excel 中使用 VBA 将某些行复制到不同工作表上的不同范围?