Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException on ByteBuffer.asCharArray().array()

Tags:

java

java-6

nio

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());

like image 401
user1568898 Avatar asked Mar 26 '26 23:03

user1568898


2 Answers

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()));
like image 153
Peter Lawrey Avatar answered Mar 31 '26 06:03

Peter Lawrey


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);
like image 23
Louis Wasserman Avatar answered Mar 31 '26 06:03

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!