50,523
社区成员
发帖
与我相关
我的任务
分享
public class Test144 {
public static void main(String[] args) {
Path path = Paths.get("E:/example.txt");
AsynchronousFileChannel AFC = null;
try {
AFC = AsynchronousFileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
} catch (IOException e) {
e.printStackTrace();
}
ByteBuffer BB = ByteBuffer.allocate(64);
AFC.read(BB, 0, BB, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] buf = new byte[attachment.limit()];
attachment.get(buf);
System.out.println(new String(buf));
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("error");
}
});
}
}
public class Test144 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("E:/example.txt");
AsynchronousFileChannel AFC = null;
try {
AFC = AsynchronousFileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer BB = ByteBuffer.allocate(64);
AFC.read(BB, 0, BB, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] buf = new byte[attachment.limit()];
attachment.get(buf);
System.out.println(new String(buf));
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("error");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public interface CompletionHandler<V,A>
A handler for consuming the result of an asynchronous I/O operation.
public interface CompletionHandler<V,A>A handler for consuming the result of an asynchronous I/O operation.
意思是说:CompletionHandler是异步处理的,如果要显示,就要让主线程等一下它