ByteArrayOutputStream for CharBuffer
I have a ByteArrayOutputStream input and need to convert it to CharBuffer.
I was trying to avoid creating a new line. Is there any way to do this.
I tried to do the following, but I don't have an encoding for the string, so the code below won't work (invalid output).
ByteBuffer byteBuffer = ByteBuffer.wrap(byteOutputStream.toByteArray());
CharBuffer document = byteBuffer.asCharBuffer();
a source to share
You must provide an encoding. How the class needs to know how to convert. There is no way to determine the encoding before writing to the ByteOutputStream, or to avoid the stream entirely. If not, you need to make assumptions and may fail.
By providing encoding you can convert a byte buffer to a char buffer
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(yourByteBuffer);
a source to share
ByteBuffer.asCharBuffer
gives you literally two byte
before char
(big or small end) with updates being displayed in both buffers.
Presumably you want to go from byte
to char
with some sensible encoding. There are many ways to do this. For example [new String (byte [], String encoding)] [1]. Basically they will go through CharsetEncoder in one form or another. Then it should be easy to get out of CharBuffer
there.
CharBuffer
- a rather low level thing. Are you sure this is really what you want?
[1]: http: // file: /// C: /Users/tackline/sun/docs/api/java/lang/String.html#String (byte [] , java.lang.String)
a source to share
ByteBuffer.asCharBuffer()
assumes the bytes are UTF-16. (I can't find anything in the docs that says this explicitly, but the implementation just treats byte pairs as low and high character bytes.) If you need a different encoding, you'll have to take a different approach.
The easiest way is to just create String
:
CharBuffer document = CharBuffer.wrap(byteOutputStream.toString(encoding));
I know you said you were trying to avoid creating a newline, but your code snippet ByteArrayOutputStream.toByteArray()
was allocating a separate byte array anyway ( "Creates a newly allocated byte array" according to the docs). Since it CharBuffer
supports random access, and many encodings (in particular UTF-8) are variable width, it's probably best to just convert the whole thing to characters anyway.
If you really need streaming access (as opposed to random access) to characters, it might CharBuffer
not be the best interface for accepting basic code.
a source to share