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
相关推荐
liujing102329298 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
Brookty11 分钟前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰25 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT25 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄28 分钟前
设计模式之外观模式
java·设计模式·外观模式
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai1 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter