public class AioFileChannel {
public static void main(String[] args) throws IOException, InterruptedException {
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data2.txt"), StandardOpenOption.READ)) {
// 参数1:ByteBuffer
// 参数2:文件开始位置
// 参数3:附件
// 参数4:回调对象
ByteBuffer buffer = ByteBuffer.allocate(64);
System.out.println("开始读取文件");
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
// 当文件正确读取到了
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("读取文件完成");
attachment.flip();
System.out.println(new String(attachment.array(), 0, result)); // 其实就是把buffer中的数据读取出来
}
// 出现异常
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("读取文件失败");
exc.printStackTrace();
}
});
System.out.println("结束读取文件");
} catch (IOException e) {
System.out.println("读取文件出现异常");
e.printStackTrace();
}
System.in.read();
}
}