gpt4 book ai didi

java - AsynchronousFileChannel 写入失败

转载 作者:行者123 更新时间:2023-12-01 12:14:30 25 4
gpt4 key购买 nike

我正在尝试使用 AsynchronousFileChannel.write 将图像写入文件:

    ...
Path filePath = Paths.get(path + "/" + System.currentTimeMillis()
+ ".jpeg");
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(filePath,
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);) {
CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

@Override
public void failed(Throwable exc, Object attachment) {
logger.error("Write failed: ", exc);
}

@Override
public void completed(Integer result, Object attachment) {
...
}
};

ByteBuf buffer = Unpooled.buffer(request.getImage().length);
buffer.writeBytes(request.getImage());
channel.write(buffer.nioBuffer(), 0, null, handler);
} catch (IOException e) {
logger.error("Failed to open file: ", e);
throw new RuntimeException(e);
}

....

我经常收到以下异常:

java.nio.channels.AsynchronousCloseException: null
at sun.nio.ch.SimpleAsynchronousFileChannelImpl$3.run(SimpleAsynchronousFileChannelImpl.java:380) ~[na:1.8.0_25]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]

我使用 Oracle JDK 8u25 在 Linux 上运行此代码。这种异常在 Windows 上发生的情况要少得多。而且我还注意到,当我在 Debug模式下运行代码时,单步执行每一行代码,这种情况很少发生。

当我不使用 CompletionHandler 时,而是使用:

    Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0);
Integer integer = writeFuture.get();

我没有得到异常(exception)。

这可能是什么原因造成的?

最佳答案

我认为这是因为当您离开 try {...} block 时会自动关闭 Channel 并且您正在进行的写入是异步的,这意味着如果您的写入完成得不够快,您将尝试写入到一个封闭的 channel 。

关于java - AsynchronousFileChannel 写入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com