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
相关推荐
CHENFU_JAVA6 分钟前
EasyExcel 合并单元格最佳实践:基于注解的自动合并与样式控制
java·excel
华仔啊1 小时前
3行注解干掉30行日志代码!Spring AOP实战全程复盘
java·spring boot·后端
Fireworkitte1 小时前
Tomcat 的核心脚本catalina.sh 和 startup.sh的关系
java·tomcat
风吹落叶32571 小时前
深入解析JVM内存管理与垃圾回收机制
java·开发语言·jvm
叶~璃1 小时前
人工智能驱动的开发变革
java
悟能不能悟2 小时前
排查Redis数据倾斜引发的性能瓶颈
java·数据库·redis
Derek_Smart2 小时前
Java线程死亡螺旋:解析与预防策略
java·spring·性能优化
翁正存2 小时前
IDEA测试代码报java file outset source root异常
java·ide·intellij-idea
励志五个月成为嵌入式糕手2 小时前
0819 使用IP多路复用实现TCP并发服务器
java·服务器·tcp/ip
Mi_Manchikkk2 小时前
Java高级面试实战:Spring Boot微服务与Redis缓存整合案例解析
java·spring boot·redis·缓存·微服务·面试