package com.example.demo.allKnowledge.nio;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelTest {
/**
* @Description:
* 开启file
* 开启file通道channel
* 开启缓冲区buffer
* channel读取放入buffer
* @Param: [args]
* @return: void
* @Author: 李小龙
* @Date: 2020/1/12
* @Time: 20:24
*/
public static void main(String[] args) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile("C:\\Users\\99499\\Desktop\\aabb.txt", "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(48);
int read = fileChannel.read(byteBuffer);
while (read!=-1){
/*
* Buffer的读写
* 1.写入数据read()到buffer
* 2.调用flip()方法切换到读模式
* 3.从buffer读取数据get()
* 4.调用clear()方法或这compact()方法
* */
System.out.println("read:"+read);
byteBuffer.flip();//改变limit和position,一般数据放入缓冲区后要读取时调用
/*
* position,capacity,limit
* 写模式w:w.capacity=w.limit
* 读模式r:r.limit=w.position,r.position=0
* */
while(byteBuffer.hasRemaining()){
System.out.println((char) byteBuffer.get());
}
byteBuffer.clear();//清除缓冲区
//byteBuffer.compact();//清除已读数据,未读数据前移,新增数据放在未读数据后面
read = fileChannel.read(byteBuffer);
}
randomAccessFile.close();
}
}