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
相关推荐
咖啡八杯9 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
用户1285261160216 小时前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
java
Linsk17 小时前
组件 = 模板 + 业务逻辑
java·前端·vue.js
星沉远浦17 小时前
用Gemini高效解决Java代码报错难以定位的问题
java
用户2986985301421 小时前
Word 文档字符级格式化:Java 实现方案详解
java·后端
笨鸟飞不快21 小时前
从单个服务到集群:一次完整的性能排查复盘
java·前端
荣码1 天前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
SamDeepThinking1 天前
Java微服务练习方式
java·后端·微服务
朦胧之1 天前
AI 编程-老项目改造篇
java·前端·后端
程序猿大帅2 天前
别再只当调包侠了:用 Spring AI 落地 Function Calling,我被大模型硬生生砸出了三个大坑
java