简体   繁体   中英

ByteArrayOutputStream vs. CharBuffer with CharSet

I am just trying to avoid some large array copies(byte[] arrays).

I have a String of size n
I have a byte[] of size m

I am using ISO-8859-1 for the String. I would very much like to write the String to byte[0] to byte[n-1] positions in this array, and then for the byte[], I will just System.arrayCopy the bytes into the array.

In looking at ByteArrayOutputStream, it is synchronized which I don't need and looking at byteBuffer.asCharBuffer(), I can't seem to supply the CharSet which I would prefer to always be explicit.

How can the above be achieved?

Also, I just found out byteBuffer.asCharBuffer assumes incorrectly that each char occupies two bytes which is not the case for ascii or ISO-8859-1 so CharBuffer in that regard is not working out too well.

thanks, Dean

The common way for writing the encoding the strings is CharsetEncoder . I believe it fits into this scenario too:

encoder = StandardCharsets.ISO_8859_1.newEncoder();
ByteBuffer result = encoder.encode(CharBuffer.wrap(inputString));
// do whatever you want with result... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM