CharBuffer.put () does not work

I am trying to put some lines in CharBuffer using the CharBuffer.put() function but the buffer remains empty.

my code is:

 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 using with clear() or rewind() after allocate(1000) , but that did not change the result.

+6
source share
4 answers

You have to rewind it after you put the objects, 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); 
+2
source

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

+3
source

Try the following:

 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 that you are missing is that the record moves the current pointer to the end of the recorded data, so when you print it, it starts with the current pointer that did not write anything.

+3
source

You will need to flip() buffer before you can read from the buffer. Before reading data from the buffer, you need to call the flip() method. When the flip() method is called the limit, the current position is set, and the position is 0. For example,

 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 characters in buffers, not in unwritten space in the buffer.

+3
source

Source: https://habr.com/ru/post/906750/


All Articles