NIO buffer 读写方法介绍

byteBuffer 继承自buffer的flip方法,
在信道为bytebuffer写入数据或者是其他put方式写入数据后,flip 为bytebuffer中的数据输出做准备。
public final Buffer flip() limit置为positioin, position置为0,
Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.
After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations. For example:
buf.put(magic); // Prepend header
in.read(buf); // Read data into rest of buffer
buf.flip(); // Flip buffer
out.write(buf); // Write header + data to channel
This method is often used in conjunction with the compact method when transferring data from one place to another.
Returns:
This buffer

也是为bytebuffer中的数据输出做准备,不过从头开始,position置为0.

public final Buffer rewind() position置为0
Rewinds this buffer. The position is set to zero and the mark is discarded.
Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately. For example:
out.write(buf); // Write remaining data
buf.rewind(); // Rewind buffer
buf.get(array); // Copy data into array
Returns:
This buffer

public abstract ByteBuffer compact()
作用是,把buffer中的position 到limit之间的数据拷贝到buffer的头部,然后position置为数据末尾的地方。为对缓冲区写入数据做准备(channel.read(buffer) or buffer.put(bytes))
Compacts this buffer (optional operation).
The bytes between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index p = position() is copied to index zero, the byte at index p + 1 is copied to index one, and so forth until the byte at index limit() - 1 is copied to index n = limit() - 1 - p. The buffer’s position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded.
The buffer’s position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method.
Invoke this method after writing data from a buffer in case the write was incomplete. The following loop, for example, copies bytes from one channel to another via the buffer buf:

buf.clear(); // Prepare buffer for use
while (in.read(buf) >= 0 || buf.position != 0) {
buf.flip();
out.write(buf);
buf.compact(); // In case of partial write
}

Returns:
This buffer

public final Buffer clear(). position置为0, limit置为capacity, 为buffer的写入数据做准备。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值