首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何关闭AsynchronousFileChannel

如何关闭AsynchronousFileChannel
EN

Stack Overflow用户
提问于 2017-11-23 02:46:58
回答 2查看 553关注 0票数 0

根据AsynchronousChannelAsynchronousFileChannel实现的API描述。

此通道上的任何未完成的异步操作都将在异常AsynchronousCloseException中完成。

因此,根据我的理解,关闭它的正确方法是将close()调用放在传递给AsynchronousFileChannel.writeCompletionHandler中,例如,如果我要通过AsynchronousFileChannel编写文件。然而,如何将通道传递给处理程序确实让我感到困惑。我应该把它作为手柄的附件传递吗?有人能给我一个示例代码吗?

EN

回答 2

Stack Overflow用户

发布于 2017-12-08 11:37:50

将通道对象作为附件传递

代码语言:javascript
复制
    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);
票数 1
EN

Stack Overflow用户

发布于 2022-01-29 08:47:22

另一种方法是使用CompletableFuture

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47446773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档