Reputation: 11744
I have an input ByteArrayOutputStream and need to convert that to a CharBuffer.
I was trying to avoid creating a new string. Is there anyway to do this.
I was trying to do the following, but I don't have the encoding for the string so the code below will not work (invalid output).
ByteBuffer byteBuffer = ByteBuffer.wrap(byteOutputStream.toByteArray());
CharBuffer document = byteBuffer.asCharBuffer();
Upvotes: 0
Views: 5174
Reputation: 10851
You have to provide an encoding. How should the class know how to convert. Can't you determine the encoding before writing to a ByteOutputStream or avoiding the stream completely. If not you have to do assumptions and might fail
Providing an encoding you can convert the byte buffer to a char buffer
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(yourByteBuffer);
Upvotes: 2
Reputation: 143314
ByteBuffer.asCharBuffer()
assumes that the bytes are UTF-16. (I can't find anything in the docs that says this explicitly, but the implementation just treats pairs of bytes as the low and high bytes of chars.) If you need another encoding you'll have to use a different approach.
The simplest approach is to just create a String
:
CharBuffer document = CharBuffer.wrap(byteOutputStream.toString(encoding));
I know you said you were "trying to avoid creating a new string", but your code snippet was allocating a separate byte array anyway (ByteArrayOutputStream.toByteArray()
"Creates a newly allocated byte array" according to the docs). Because CharBuffer
supports random access and many encodings (notably UTF-8) are variable-width, it's probably best to just convert the whole thing to chars upfront anyway.
If you really just want streaming access (as opposed to random access) to the characters then perhaps CharBuffer
isn't the best interface for the underlying code to accept.
Upvotes: 0
Reputation: 147164
ByteBuffer.asCharBuffer
gives you a very literal two byte
s to char
(big or little endian) with updates reflected in both buffers.
Presumably you want to go from byte
s to char
s through some reasonable encoding. There are many ways to do that. For instance [new String(byte[], String encoding)][1]. Mostly they will go through CharsetEncoder in some form. Then it should be straightforard to get a CharBuffer
from there.
CharBuffer
is a quite low-level sort of thing. Are you sure that is really what you want?
[1]: http://file:///C:/Users/tackline/sun/docs/api/java/lang/String.html#String(byte[], java.lang.String)
Upvotes: 0