3

Could someone be so kind to explain why on the following line I have UnsupportedOperationException?

System.out.println(ByteBuffer.wrap(new byte[] {'t', 'e', 's', 't', '\n'}).asCharBuffer().array());

typ1232
  • 5,535
  • 6
  • 35
  • 51
user1568898
  • 31
  • 1
  • 2

2 Answers2

3

The asCharBuffer doesn't wrap a char[] so you cannot obtain its array()

It appears what you are trying to do is.

System.out.println(Arrays.toString("test\n".toCharArray()));
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Actually I'm reading FileChannel with ByteBuffer (know for sure it is text file) and would like to have CharBuffer from ByteBuffer. If I cannot do it, what is the reason to have the method? And second question how to do it in a right way? Thank you. – user1568898 Aug 01 '12 at 15:05
  • When you build a CharBuffer which is a wrapper for an `char[]` you can use `array()` to get the original array you built the buffer from. – Peter Lawrey Aug 01 '12 at 15:07
  • Something like http://stackoverflow.com/questions/5936275/fast-bytebuffer-to-charbuffer-or-char ? – Peter Lawrey Aug 01 '12 at 15:08
  • Note, you have the problem that you must read a whole number of characters, which can be tricky if you have a multi-byte character encoding, unless you read everything before decoding. – Peter Lawrey Aug 01 '12 at 15:09
3

Did you read the Javadoc for CharBuffer.array()?

Not all CharBuffers are backed by a char[]. ByteBuffer.asCharBuffer() returns a view of the ByteBuffer as a CharBuffer, so its result is backed by a byte[].

array() only returns the char[] that actually backs the buffer, and if none exists, it throws a UOE. The closest alternative you'll be able to get is something like

char[] result = new char[charBuf.remaining()];
charBuf.get(result);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413