I am aware that flip() set the current buffer position to 0 and set the limit to the previous buffer position whereas rewind() just set the current buffer position to 0.
In the following code, either I use rewind() or flip() i get the same result.
byte b = 127; bb.put(b); bb.rewind();//or flip(); System.out.println(bb.get()); bb.rewind();// or flip(); System.out.println(bb.get());
Could you provide me with a real example where the difference of these 2 methods really matters? Thanks in advance.
ByteBuffer rewind() methods in Java with Examples The rewind() method of java. nio. ByteBuffer Class is used to rewind 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.
There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files.
A ByteBuffer is a buffer which provides for transferring bytes from a source to a destination. In addition to storage like a buffer array, it also provides abstractions such as current position, limit, capacity, etc. A FileChannel is used for transferring data to and from a file to a ByteBuffer.
ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.
From the source code, they are very similar. You can see the follow:
public final Buffer flip() { limit = position; position = 0; mark = -1; return this; } public final Buffer rewind() { position = 0; mark = -1; return this; }
So the difference is the flip
set the limit
to the position
, while rewind
not. Consider you have allocated a buffer with 8 bytes, you have filled the buffer with 4 bytes, then the position is set to 3, just show as follow:
[ 1 1 1 1 0 0 0 0] | | flip limit | rewind limit
So rewind
just used limit has set appropriately.
They're not equivalent at all.
A ByteBuffer
is normally ready for read()
(or for put()
).
flip()
makes it ready for write()
(or for get()
).
rewind()
and compact()
and clear()
make it ready for read()/put()
again after write()
(or get()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With