温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java nio缓冲区怎么用

发布时间:2026-09-02 13:17:09 来源:亿速云 阅读:90 作者:小樊 栏目:编程语言

Java NIO(New I/O)里的**缓冲区(Buffer)**是核心概念之一,所有数据的读写都要经过 Buffer。下面从概念、常用类、基本用法到示例给你讲清楚。


一、Buffer 是什么

Buffer 是一个线性、有限的容器,用于临时存放数据。
在 NIO 中:

  • 写数据:先写入 Buffer
  • 读数据:再从 Buffer 读取

常见 Buffer 类型:

  • ByteBuffer(最常用)
  • CharBuffer
  • IntBuffer
  • DoubleBuffer

二、Buffer 的三个核心属性

理解这三个属性非常关键:

属性 含义
capacity 缓冲区最大容量(创建后不可变)
limit 当前可操作数据的边界
position 当前读写位置

关系:

0 <= position <= limit <= capacity

三、Buffer 的基本使用步骤

1️⃣ 创建 Buffer

ByteBuffer buffer = ByteBuffer.allocate(1024); // 堆内存
// 或
ByteBuffer buffer = ByteBuffer.allocateDirect(1024); // 直接内存(性能更好)

2️⃣ 写数据到 Buffer

buffer.put("Hello".getBytes());

或者通过 Channel 写:

channel.read(buffer);

3️⃣ 切换为读模式(flip)

⚠️ 非常重要

buffer.flip();

作用:

  • position 设为 0
  • limit 设为当前 position

4️⃣ 从 Buffer 读数据

byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(new String(bytes));

或通过 Channel 写:

channel.write(buffer);

5️⃣ 清空 Buffer

buffer.clear();      // 清空,可重新写
// 或
buffer.compact();    // 保留未读数据

四、完整示例(文件读写)

写入文件

try (FileChannel channel =
     FileChannel.open(Paths.get("test.txt"),
             StandardOpenOption.CREATE,
             StandardOpenOption.WRITE)) {

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    buffer.put("Hello NIO".getBytes());
    buffer.flip();

    channel.write(buffer);
} catch (IOException e) {
    e.printStackTrace();
}

读取文件

try (FileChannel channel =
     FileChannel.open(Paths.get("test.txt"), StandardOpenOption.READ)) {

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    int read = channel.read(buffer);

    buffer.flip();
    byte[] data = new byte[buffer.remaining()];
    buffer.get(data);
    System.out.println(new String(data));
} catch (IOException e) {
    e.printStackTrace();
}

五、常见坑点总结

✅ 写完必须 flip() 才能读
✅ 读完考虑 clear()compact()
remaining() = limit - position
allocateDirect 适合大文件、长生命周期


六、Buffer 常用方法速查

buffer.put()
buffer.get()
buffer.flip()
buffer.clear()
buffer.compact()
buffer.rewind()
buffer.mark()
buffer.reset()
buffer.remaining()

如果你愿意,我可以:

  • 图解方式 讲 position/limit
  • Netty 中的 ByteBuf
  • 或结合 SocketChannel 写完整通信示例

你想看哪一个?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI