Java NIO Buffer详解

在 Java NIO 中,Buffer 是一个用于存储数据的容器对象,通常用于读取和写入数据。Buffer 本质上是一个数组,但它提供了一些便捷的方法来读写数据,并跟踪已读取或已写入的位置。

Buffer 的常用属性包括:

  • capacity:缓冲区容量
  • position:下一个可读或写的位置
  • limit:可读或写的最大位置

Buffer的基本用法,使用Buffer读写数据一般遵循以下四个步骤:

1 写入数据到Buffer
2 调用flip()方法
3 从Buffer中读取数据
4 调用clear()方法或者compact()方法

常用API:

  • allocate(capacity)
  • put()
  • get()
  • compact()
  • capacity()
  • hasRemaining()
  • limit()
  • mark()
  • position()
  • remainig()
  • reset()
  • rewind()
  • clear()
  • flip()

Buffer 有多个子类,包括 ByteBuffer、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer 和 DoubleBuffer 等,用于存储不同类型的数据。以下是一个使用 ByteBuffer 进行读写操作的示例:

// 创建一个 ByteBuffer
ByteBuffer buf = ByteBuffer.allocate(1024);

// 写入数据
String data = "Hello, World!";
buf.put(data.getBytes());

// 切换为读模式
buf.flip();

// 读取数据
byte[] bytes = new byte[buf.limit()];
buf.get(bytes);
String str = new String(bytes);
System.out.println(str);

// 清空缓冲区
buf.clear();

在这个示例中,我们首先创建了一个 1024 字节的 ByteBuffer,然后通过 put() 方法向其中写入字符串数据。接着,我们使用 flip() 方法切换为读模式,并使用 get() 方法读取数据。最后,我们通过 clear() 方法清空缓冲区,以便再次写入数据。