buffer

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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值