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
相关推荐
孔明兴汉34 分钟前
第一章-第三节-Java开发环境配置
java·开发语言
小王不爱笑1321 小时前
Java 核心知识点查漏补缺(一)
java·开发语言·python
空空kkk1 小时前
Java——类和对象
java·开发语言
JIngJaneIL1 小时前
篮球论坛|基于SprinBoot+vue的篮球论坛系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·篮球论坛系统
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 安卓的服装销售APP为例,包含答辩的问题和答案
java·eclipse·tomcat
青云交3 小时前
Java 大视界 -- Java 大数据在智能农业温室环境调控与作物生长模型构建中的应用
java·机器学习·传感器技术·数据处理·作物生长模型·智能农业·温室环境调控
曾经的三心草3 小时前
SpringAI5-智能聊天机器⼈
java·springai
微露清风3 小时前
系统性学习C++-第八讲-vector类
java·c++·学习
roykingw3 小时前
【思想比实现更重要】高并发场景下如何保证接口幂等性
java·web安全·面试
864记忆4 小时前
Spring Boot 项目标准目录结构
java