我尝试使用来自/ dev / tty的NIO.2异步IO,但在下面的代码中,read不会阻塞:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
public class AsyncKbd {
public static void main(String[] args) throws IOException {
AsynchronousFileChannel kbd = AsynchronousFileChannel.open(Paths.get("/dev/tty"),
StandardOpenOption.READ);
CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer i, ByteBuffer buffer) {
System.out.print(new String(buffer.array()));
}
public void failed(Throwable exc, ByteBuffer buffer) {
}
};
ByteBuffer buffer = ByteBuffer.allocate(80);
kbd.read(buffer, 0, buffer, handler);
}
}
我怀疑由于/ dev / tty是一个设备,文件位置参数(0)等于大小(通常也是0)并且读取不会阻塞。那么如何从键盘编程异步读取+回调处理程序?