<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.39.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.11.3</version>
</dependency>
package com.example.nettytest.nio.day1;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description:
* @author: xz
* @create: 2022-07-18 22:17
*/
@Slf4j
public class TestByteBuffer {
public static void main(String[] args) {
//FileChannel
try (FileChannel channel = new FileInputStream("test.txt").getChannel()) {
//allocate:分配一个新的字节缓冲区,容量为10
ByteBuffer buffer = ByteBuffer.allocate(10);
while(true){
// 从 channel 读取数据,向 buffer 写入
int len = channel.read(buffer);
log.info("读取到的字节数 {}", len);
if(len ==-1){
break;
}
// 打印 buffer 的内容
buffer.flip();// 切换至读模式
while (buffer.hasRemaining()){// 是否还有剩余未读数据
byte b = buffer.get();
log.info("实际字节 {}", (char) b);
}
buffer.clear(); // 切换为写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://wwwxz.blog.csdn.net/article/details/125861836
内容来源于网络,如有侵权,请联系作者删除!