NIO

基本读

代码

try (FileChannel channel = new FileInputStream(getClass()
            .getResource("/test.txt")
            .getPath()).getChannel()) {
    log.error(getClass().getResource("/test.txt").getPath());

    while (true) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        int len = channel.read(buffer);
        if (len == -1) {
            break;
        }
        buffer.flip();//切换到读模式
        while (buffer.hasRemaining()) { //判断是否还有没有读的数据
            byte b = buffer.get();
            log.error("读取:{}", (char) b);
        }
        buffer.clear();//切换到写模式
    }

} catch (IOException e) {
    e.printStackTrace();
}

ByteBuffer 的使用

  1. 向buffer写入数据
  2. 调用flip() 切换到读模式
  3. 从buffer读取数据
  4. 调用clear()或compace() 切换到写模式

buffer重要属性

  • capacity 容量
  • postion 当前位置
  • Limit 能写入的限制

ByteBuffer 常用方法

  • ByteBuffer.allocate(20) 分配大小,不能调整大小 HeapByteBuffer 堆内存, 读写效率低,会垃圾回收(整理后更有序)
  • ByteBuffer.allocateDirect(200) // DirectByteButter 直接内存 ,读写高,不会回收,分配效率低,会内存泄露
  • get 读取
  • put 写入 chnnel.read()
  • rewind() 置postion为0,可以重复读
  • mark() 设置一个mark标记位
  • reset() 重置读位置到mark
  • StandardCharsets.UTF_8.encode(“hello”) 生成ByteBuffer对象到读模式
  • ByteBuffer buffer= ByteBuffer.wrap(“hello”.getBytes()) 生成byteBuffer对象,到读模式
  • StandardCharsets.UTF_8.decode(buffer) buffer生成字符串