Java 异步文件通道写入失败
我正在尝试使用AsynchronousFileChannel将图像写入文件。写入:Java 异步文件通道写入失败,java,netty,nio2,Java,Netty,Nio2,我正在尝试使用AsynchronousFileChannel将图像写入文件。写入: ... Path filePath = Paths.get(path + "/" + System.currentTimeMillis() + ".jpeg"); try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(filePath, StandardOpen
...
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);
}
....
我使用Oracle JDK 8u25在Linux上运行此代码。这是在Windows上很少出现的例外情况。我还注意到,当我在调试模式下运行代码时,在每一行代码上单步执行时,这种情况很少发生
如果我不使用CompletionHandler,而是使用:
Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0);
Integer integer = writeFuture.get();
Future writeFuture=channel.write(buffer.nioBuffer(),0);
整数=writeFuture.get();
我没有例外
这可能是什么原因造成的?我认为这是因为当您离开try{…}块时,会自动关闭通道,并且您正在进行的写入是异步的,这意味着如果写入速度不够快,您将尝试写入一个关闭的通道
Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0);
Integer integer = writeFuture.get();