I am new to ByteBuffer and I am confuse about buffer.flip() usage.
- I know that flip set the limit to position, and position to zero so I think it could be usefull in situations where I have the buffer not full and I read and also write in the buffer, so I preserve the read space and write space, is it right?
- In a situation where I am sure that I don't do any read or write until the buffer is completly full or completly empty, is still usefull to flip?
I tested the following code that return the same result (assume no problem with readyBytes > 0 and also channel.read give me the entire message. ASSUME that the buffer became full in the following examples, this are extracted from my entire code):
Example 1:
int readBytes = channel.read(buffer);
String message = new String(buffer.array(), 0, buffer.array().length, StandardCharsets.UTF_8);
Example 2:
int readBytes = channel.read(buffer);
buffer.flip();
String message = new String(buffer.array(), 0, buffer.array().length, StandardCharsets.UTF_8);
What code should I use?
The previous example are a small part, in reality I should write the buffer content in another channel so I will do a out.write(buffer), is there differences between out.write(buffer) operation and transforming the buffer content to a string?