我正在尝试使用 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 上发生的异常少得多。而且我还注意到,当我在调试模式下运行代码时,遍历每一行代码,这种情况很少发生。
当我不使用 CompletionHandler,而是使用:
Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0);
Integer integer = writeFuture.get();
我没有得到例外。
这可能是什么原因造成的?