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
相关推荐
宠友信息3 分钟前
内容社区源码开发实践解析,用Spring Boot打造1:1仿小红书源码平台
java·spring boot·redis·websocket·mysql·spring·uni-app
行百里er16 分钟前
加个依赖就生效?一行搞定 Spring Boot Starter 自动装配
java·后端·监控
月华路22 分钟前
G1 新生代对象晋升老年代:实现机制与 GC 日志
java·jvm·算法
AI人工智能+电脑小能手1 小时前
大白话说Java设计模式-34-命令模式(业务实战篇)
java·spring·设计模式·命令模式·异步任务·撤销重做·事务封装
净重21克1 小时前
万字长文!TLS协议升级避坑手册:JDK老项目适配TLS1.2/1.3全流程拆解
java·springboot·java安全
一直C1 小时前
【数据结构】哈希表+算法复杂度与经典排序查找(C语言)
java·linux·开发语言·数据结构·算法·ubuntu·散列表
paopaokaka_luck1 小时前
基于springboot3+vue3的车间生产管理系统(Echarts图形化分析、BI报表)
java·前端·spring boot·学习·echarts
Zane19942 小时前
遍历时删元素为什么报错:modCount 这个"计数器"在背后盯着你
java·后端
电商API_180079052472 小时前
速卖通商品采集API技术文章
java·开发语言·c++·api·跨境电商·商品详情
郑州光合科技余经理2 小时前
海外版外卖系统架构:订单怎么流转、权限怎么分
java·开发语言·前端·系统架构·uni-app·php·ai编程