我想通过网址下载几张照片,使用Webflux和AsynchronousFileChannel,所有的文件都是创建的,但为空。
下面是我的代码:
public void downloadFilesFromUrl() throws IOException {
List<Photo> notDownloadedFiles = //get photos with name and URL;
for (Photo photo : notDownloadedFiles) {
Path path = Paths.get(pathToFiles + File.separator + photo.getPhotoName());
WebClient client = WebClient.builder().baseUrl(photo.getLoadSource()).build();
Flux<DataBuffer> dataBufferFlux = client
.get().accept(MediaType.APPLICATION_OCTET_STREAM)
.retrieve()
.bodyToFlux(DataBuffer.class);
saveFileOnComputer(path, dataBufferFlux);
}
}
private void saveFileOnComputer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel)
.doOnNext(DataBufferUtils.releaseConsumer())
.doAfterTerminate(() -> {
try {
asynchronousFileChannel.close();
} catch (IOException ignored) { }
}).then();
}如果我尝试使用
DataBufferUtils.write(dataBufferFlux, path, StandardOpenOption.CREATE).block();而不是调用saveFileOnServer(..)方法,一切都很好。但我想确切地使用AsynchronousFileChannel。
发布于 2021-04-28 01:57:39
好吧,我想我把它修好了。
private void saveFileOnServer(Path path, Flux<DataBuffer> dataBufferFlux) throws IOException {
AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, CREATE, WRITE);
DataBufferUtils.write(dataBufferFlux, asynchronousFileChannel).subscribe();
}官方documentation说:“请注意,直到订阅了返回的Flux,写入过程才会开始”。
https://stackoverflow.com/questions/67285154
复制相似问题