Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CharBuffer.put() didn't working

Tags:

java

put

buffer

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.

like image 943
zeevblu Avatar asked Jan 24 '12 10:01

zeevblu


3 Answers

Add a call to rewind() right after the loop.

like image 143
NPE Avatar answered Sep 20 '22 21:09

NPE


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.

like image 43
Cyberfox Avatar answered Sep 16 '22 21:09

Cyberfox


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.

like image 34
Suresh Kumar Avatar answered Sep 19 '22 21:09

Suresh Kumar