0

I am new to ByteBuffer and I am confuse about buffer.flip() usage.

  1. 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?
  2. 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?

user4789408
  • 1,196
  • 3
  • 14
  • 31
  • @starikoff I already read this post but this doesn't answer my question because doesn't explain a lot more then what is written on Java doc – user4789408 Dec 01 '19 at 16:29
  • @starikoff also my question is more structured with three questions – user4789408 Dec 01 '19 at 16:31
  • I repeat. *Both* your samples are wrong, as you should have already discovered under test. 1. You need the `flip()`, and (2) the correct length is given here by `readBytes`, not by `buffer.array().length`. It continues to baffle me why correct factual information keeps getting deleted here. – user207421 Dec 03 '19 at 00:56

0 Answers0