码迷,mamicode.com
首页 > 其他好文 > 详细

ByteBuffer详解

时间:2018-08-12 15:48:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ini   logs   etc   com   stat   限制   random   rac   源码   

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

字段:  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");
    }
}

 

ByteBuffer详解

标签:ini   logs   etc   com   stat   限制   random   rac   源码   

原文地址:https://www.cnblogs.com/coder-lzh/p/9462750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!