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
相关推荐
q***465232 分钟前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge99932 分钟前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***252133 分钟前
Spring Boot接收参数的19种方式
java·spring boot·后端
WX-bisheyuange33 分钟前
基于Spring Boot的民谣网站的设计与实现
java·spring boot·后端
q***146437 分钟前
Spring Boot文件上传
java·spring boot·后端
WX-bisheyuange3 小时前
基于Spring Boot的民宿预定系统的设计与实现
java·spring boot·后端·毕业设计
码界奇点3 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程
q***9444 小时前
springboot接入deepseek深度求索 java
java·spring boot·后端
诗9趁年华4 小时前
深入分析线程池
java·jvm·算法
百***06014 小时前
SpringBoot的@Scheduled和@Schedules有什么区别
java·spring boot·spring