12.NIO-AIO文件异步

1.5.6、文件异步AIO
@Slf4j
public class AIOTest {
    public static void main(String[] args) {
        try {
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("a.txt"));

            ByteBuffer buffer = ByteBuffer.allocate(128);
            //buffer 开始位置 附件 回调方法
            log.debug("read begin..");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                //result:读到的字节数
                //attachment:附件
                @Override//成功回调
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read succ..");
                   /* attachment.flip();
                    ByteBufferUtil.debugAll(attachment);*/

                    attachment.flip();
                    byte[] data = new byte[attachment.limit()];
                    attachment.get(data);
                    System.out.println(new String(data));
                    attachment.clear();
                }

                @Override//失败回调
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end..");
            System.in.read();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
posted @   jpy  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
历史上的今天:
2021-10-12 阿里云的这群疯子
点击右上角即可分享
微信分享提示