ByteBuffer详解

时间:2023-03-09 04:20:30
ByteBuffer详解

注意:一定要了解这个缓冲类的几个方法和那几个字段。不然你不会明白的。

字段:  position ,limit ,mark
方法:clear(), hasRemaining(),flip()

推荐博客:讲的很详细 https://www.cnblogs.com/jiduoduo/p/6397454.html

看代码:

package Test;

import org.junit.Test;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset; /**
* Created by 敲代码的卡卡罗特
* on 2018/8/12 0:49.
*/
public class ByteBufferDemo {
//主要通过读取文件内容,写到ByteBuffer里,然后再从ByteBuffer对象中获取数据,显示到控制台 public static void readFile(String fileName) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while(fileChannel.read(byteBuffer)>0){
//把ByteBuffer从写模式,转变成读取模式,即使把position的位置变成0,limit的位置变成position。因为这时候
//已经把数据读到缓冲区了,所以要复位一下,才能读。
byteBuffer.flip();
//下面这两个是把缓冲区的数据打印下来
Charset charset = Charset.forName("UTF-8");
System.out.println(charset.newDecoder().decode(byteBuffer).toString());
//这个并不是把缓冲区的数据清除,看源码就知道了,还是指针的位移。把position为0,把limit为缓冲区的设置的最大限制
byteBuffer.clear();
}
fileChannel.close();
randomAccessFile.close();
} catch (Exception e) {
e.printStackTrace();
} } @Test
public void test(){
readFile("G:\\IDEAworkspace\\springboot-jpa\\src\\test\\java\\Test\\Base64.java");
}
}