Is there an OutputStreamWriter without buffering?

I need to convert a char stream to a byte s stream, i.e. I need an adapter from the java.io.Writer interface to java.io.OutputStream that supports any valid Charset that I will have as a configuration parameter.

However, the java.io.OutputStreamWriter class has a hidden secret: the sun.nio.cs.StreamEncoder object, which it delegates by creating a buffer of 8192 bytes (8 KB), even if you don't ask for it.

The problem is that at the end of the OutputStream I inserted a wrapper that should count the number of bytes written, so that it immediately stops the execution of the source system after a certain number of bytes are issued. And if OutputStreamWriter creates an 8K buffer, I just get a notification about the number of bytes generated too late , because they will only reach my counter when the buffer is flushed (so that there will be more than 8,000 already generated bytes waiting for me in the buffer OutputStreamWriter ).

So the question is, is there somewhere in the Java runtime a Writer OutputStream bridge that can run unbuffered ?

I really, really hate writing it myself: (...

NOTE : clicking flush () on the OutputStreamWriter for each record is not a valid alternative. This leads to a large performance penalty (there is a synchronized block involved in StreamEncoder ).

NOTE 2 I understand that a surplus on the char bridge may be required to calculate surrogates. This is not that I need to stop the execution of the source system at the moment when it generates the nth byte (it would not be possible if the bytes could come to me as a larger byte[] in a write call). But I need to stop it as soon as possible, and waiting for a buffer of 8K, 2K or even 200 bytes will be just too late.

+6
source share
1 answer

As you have already determined, the StreamEncoder used by OutputStreamWriter has a buffer size of 8 KB and there is no interface for changing this size.

But the following snippet gives you a way to get a Writer for an OutputStream , which internally also uses StreamEncoder , but now has a user-defined buffer size:

 String charSetName = ... CharsetEncoder encoder = Charset.forName(charSetName).newEncoder(); OutputStream out = ... int bufferSize = ... WritableByteChannel channel = Channels.newChannel(out); Writer writer = Channels.newWriter(channel, encoder, bufferSize); 
+7
source

All Articles