实现说明
整个示例围绕类 AsyncFileRead和函数 completed、failed组织。
资源写在 try 头部,关闭由编译器生成、异常安全。
使用要点
- 直接运行文件,输出会带上标签,比如
bytes:、failed:——输出的每一行都能指回产生它的那次调用。 main按顺序串起completed、failed;运行文件就会把这个流程跑一遍。
常见问题
运行「AsynchronousFileChannel 回调读取」会打印什么?
整个文件跑完,输出行以 bytes:、failed: 这类前缀开头。
主签名形如 public void completed(Integer bytes, ByteBuffer buf)
核心语句
Files.writeString(file, "async read demo", StandardCharsets.UTF_8);
Path file = Files.createTempFile("note-", ".txt");
ByteBuffer buffer = ByteBuffer.allocate(16);
代码示例
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
public class AsyncFileRead {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("note-", ".txt");
Files.writeString(file, "async read demo", StandardCharsets.UTF_8);
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(
file, StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(16);
CountDownLatch done = new CountDownLatch(1);
// 回调在完成线程触发:发起后调用线程不被 IO 阻塞
channel.read(buffer, 0, buffer, new CompletionHandler<>() {
@Override
public void completed(Integer bytes, ByteBuffer buf) {
buf.flip();
System.out.println("bytes: " + bytes);
System.out.println(StandardCharsets.UTF_8.decode(buf));
done.countDown();
}
@Override
public void failed(Throwable exc, ByteBuffer buf) {
System.out.println("failed: " + exc.getMessage());
done.countDown();
}
});
done.await(); // 等回调落地再退出
}
Files.deleteIfExists(file);
}
}