I try to put some strings to CharBuffer
with CharBuffer.put()
function
but the buffer is left blank.
my code:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
System.out.println(charBuf);
I tried to use with clear()
or rewind()
after allocate(1000)
but that did not change the result.
Add a call to rewind()
right after the loop.
Try this:
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.rewind();
System.out.println(charBuf);
The detail you're missing is that writing moves the current pointer to the end of the written data, so when you're printing it out, it's starting at the current pointer, which has nothing written.
You will need to flip()
the buffer before you can read from the buffer. The flip()
method needs to be called before reading the data from the buffer. When the flip()
method is called the limit is set to the current position, and the position to 0. e.g.
CharBuffer charBuf = CharBuffer.allocate(1000);
for (int i = 0; i < 10; i++)
{
String text = "testing" + i + "\n";
charBuf.put(text);
}
charBuf.flip();
System.out.println(charBuf);
The above will only print the characters in the buffers and not the unwritten space in the buffer.
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