Netty NIO ByteBuffer 简单实验

1.概要

准备学一下Netty,先从NIO的三大组件开始。先ByteBuffer

2.代码

2.1 主函数

复制代码
package com.xjc.springcloundtest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static void main(String[] args) throws IOException {
        FileChannel channel = new FileInputStream("4.txt").getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        while (true){
            int len = channel.read(byteBuffer);
            System.out.println("读取的字节数:"+len);
            if(len==-1){
                break;
            }
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()){
                byte b = byteBuffer.get();
                System.out.println((char)b);
            }
            byteBuffer.clear();
        }

        System.out.println("Hello world!");
    }
}

2.2 准备的文件(4.txt)

复制代码
123456789abc

3.运行结果

复制代码
C:\Users\ThinkPad\.jdks\openjdk-21.0.2\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2023.3.2\lib\idea_rt.jar=51792:D:\Program Files\JetBrains\IntelliJ IDEA 2023.3.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\ThinkPad\IdeaProjects\untitled12\target\classes com.xjc.springcloundtest.Main
读取的字节数:10
1
2
3
4
5
6
7
8
9
a
读取的字节数:2
b
c
读取的字节数:-1
Hello world!

Process finished with exit code 0
相关推荐
ChaHae-In31 分钟前
MyBatis入门操作
java·mybatis
xcLeigh36 分钟前
Go入门:短变量声明的陷阱与最佳实践
java·redis·golang·教程·变量
青山木42 分钟前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年1 小时前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
szephyr1 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云
云烟成雨TD1 小时前
Micrometer 系列【39】链路追踪:入门案例 | 环境准备
java·云原生·链路追踪
chuan.bai1 小时前
Java RAG 实战(第 3 篇):从交互式聊天到多轮上下文
java·人工智能·macos·ai
952361 小时前
Sentinel
java·后端·spring·sentinel·springcloud
阿pin1 小时前
Java随笔-JDK7 HashMap头插法为何能导致死循环?
java·开发语言·hashmap
李可以量化2 小时前
Tornado 从了解到精通(一)下:异步与非阻塞 IO 核心原理
java·数据库·tornado