Java NIO(二)ByteBuffer的flip、rewind方法

首先看代码:

public class ByteBufferTry {

	public static void main(String args[]) {
		byte[] ba = new byte[10];
		Arrays.fill(ba, (byte)0);
		ByteBuffer bb = ByteBuffer.wrap(ba);
		
		System.out.println(bb);
		
		bb.putInt(10);
		
		System.out.println(bb);
		
		System.out.println(bb.getInt());
		
		System.out.println(bb);
	}
}

这段代码输出的结果为:

java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]
java.nio.HeapByteBuffer[pos=4 lim=10 cap=10]
0
java.nio.HeapByteBuffer[pos=8 lim=10 cap=10]

我们本来是期望将数值10从bb中读出,可是却读出一个0。为什么会这样?因为在putInt后,position(pos)移动到了索引4的位置,如果不做flip然后直接读的话,会读到存储在索引4-7的值,因为前面对ba清零了,所以读出了0值。

如果想读到10这个值,我们需要调用ByteBuffer::flip方法。这个方法会将limit设置成当前的position,然后将position设置为0,这样我们就能读到索引0-3的值。代码如下:

public class ByteBufferTry {

	public static void main(String args[]) {
		byte[] ba = new byte[10];
		Arrays.fill(ba, (byte)0);
		ByteBuffer bb = ByteBuffer.wrap(ba);
		
		System.out.println(bb);
		
		bb.putInt(10);
		
		System.out.println(bb);
		
		bb.flip();
		
		System.out.println(bb.getInt());
		
		System.out.println(bb);
	}
}

输出结果为:

java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]
java.nio.HeapByteBuffer[pos=4 lim=10 cap=10]
10
java.nio.HeapByteBuffer[pos=4 lim=4 cap=10]

这样就是我们需要的结果了。

如果我们想再次读出值10,我们要调用rewind函数,这个函数会将ByteBuffer的position设置成0,代码如下:

public class ByteBufferTry {

	public static void main(String args[]) {
		byte[] ba = new byte[10];
		Arrays.fill(ba, (byte)0);
		ByteBuffer bb = ByteBuffer.wrap(ba);
		
		System.out.println(bb);
		
		bb.putInt(10);
		
		System.out.println(bb);
		
		bb.flip();
		
		System.out.println(bb.getInt());
		
		System.out.println(bb);
		
		bb.rewind();
		
		System.out.println(bb.getInt());
		
		System.out.println(bb);
	}
}

输出的结果为:

java.nio.HeapByteBuffer[pos=0 lim=10 cap=10]
java.nio.HeapByteBuffer[pos=4 lim=10 cap=10]
10
java.nio.HeapByteBuffer[pos=4 lim=4 cap=10]
10
java.nio.HeapByteBuffer[pos=4 lim=4 cap=10]
posted @ 2020-11-09 10:49  ralgo  阅读(925)  评论(0)    收藏  举报