根据AsynchronousChannel的AsynchronousFileChannel实现的API描述。
此通道上的任何未完成的异步操作都将在异常
AsynchronousCloseException中完成。
因此,根据我的理解,关闭它的正确方法是将close()调用放在传递给AsynchronousFileChannel.write的CompletionHandler中,例如,如果我要通过AsynchronousFileChannel编写文件。然而,如何将通道传递给处理程序确实让我感到困惑。我应该把它作为手柄的附件传递吗?有人能给我一个示例代码吗?
发布于 2017-12-08 11:37:50
将通道对象作为附件传递
Path path = Paths.get("hello_world.txt");
path.toFile().createNewFile();
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
channel.write(ByteBuffer.wrap("hello".getBytes()), 0, channel, new CompletionHandler<Integer, Closeable>() {
@Override
public void completed(Integer result, Closeable closeMe) {
System.out.println("Written: " + result);
try {
closeMe.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Closeable closeMe) {
System.err.println("Error occurred: " + exc);
try {
closeMe.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
//wait for async task to complete
Thread.sleep(5000L);发布于 2022-01-29 08:47:22
另一种方法是使用CompletableFuture。
AsynchronousFileChannel channel = open(...);
final CompletableFuture<Void> future = new CompletableFuture();
channel.(read|write)(buffer, position, whatever, new CompletionHandler<Whatever>() {
@Override
public void completed(Integer result, Whatever attachment) {
// Do whatever you need to do...
// When completed, do
future.complete(null);
}
@Override
public void failed(Throwable exc, Whatever attachment) {
future.completeExceptionally(exc);
}
);
future.get(); // done; either with a result or an exception
channel.close();https://stackoverflow.com/questions/47446773
复制相似问题