Question

I want to write a CharSequence to OutputStream using a specified CharSet. Basically what a Writer initialized with the same CharSet would do, when write(String) is called.

The catch is, there are many CharSequences to be written and some are pretty large. To complicate matters more everything may be written to multiple OutputStream's. I can easily implement that by using (actually I currently have implemented it that way):

byte[] rawBytes = CharSequence.toString().getBytes(CharSet)
for (OutputStream out : outputTargets) {
    out.write(rawBytes);
}

But obviously the String is a totally unwanted garbage object here, as is the byte[] array. I'm looking for a method that allows me to do the encoding directly without intermediate objects. Surprisingly this seems to be impossibly - everywhere I looked in the JRE where a CharSequence is accepted it gets quickly converted into a String before any work is done.

Most (all?) of the conversion work for the CharSet seems to be done in non-public classes, so I haven't found any way to access any of that in a transparent and legal way.

How can the garbage be avoided / the JRE's CharSet encoding facilities be used directly?

Was it helpful?

Solution 2

Iterate over the characters of the sequence and write them to a writer.

OutputStream outputStream = ....
CharSequence charSequence = ....
Charset charset = ....

Writer writer = new OutputStreamWriter(outputStream, charset);

for (int i = 0; i < charSequence.length(); i++) {
    writer.write(charSequence.charAt(i));
}

OTHER TIPS

You can use Charset to encode a CharSequence to a byte array:

private static byte[] encodeUtf8(CharSequence cs) {
    ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(cs));
    byte[] result = new byte[bb.remaining()];
    bb.get(result);
    return result;
}

If, instead of OutputStream, you're using an instance of WritableByteChannel, its write method takes ByteBuffer directly, so you don't even need to copy the byte buffer to a byte array first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top