{@link OutputStream} implementation that transforms a byte stream to acharacter stream using a specified charset encoding and writes the resulting stream to a {@link Writer}. The stream is transformed using a {@link CharsetDecoder} object, guaranteeing that all charsetencodings supported by the JRE are handled correctly.
The output of the {@link CharsetDecoder} is buffered using a fixed size buffer.This implies that the data is written to the underlying {@link Writer} in chunksthat are no larger than the size of this buffer. By default, the buffer is flushed only when it overflows or when {@link #flush()} or {@link #close()}is called. In general there is therefore no need to wrap the underlying {@link Writer}in a {@link java.io.BufferedWriter}. {@link WriterOutputStream} can alsobe instructed to flush the buffer after each write operation. In this case, all available data is written immediately to the underlying {@link Writer}, implying that the current position of the {@link Writer} is correlated to the current positionof the {@link WriterOutputStream}.
{@link WriterOutputStream} implements the inverse transformation of {@link java.io.OutputStreamWriter}; in the following example, writing to out2 would have the same result as writing to out directly (provided that the byte sequence is legal with respect to the charset encoding):
OutputStream out = ... Charset cs = ... OutputStreamWriter writer = new OutputStreamWriter(out, cs); WriterOutputStream out2 = new WriterOutputStream(writer, cs);
{@link WriterOutputStream} implements the same transformation as {@link java.io.InputStreamReader}, except that the control flow is reversed: both classes transform a byte stream into a character stream, but {@link java.io.InputStreamReader} pulls data from the underlying stream,while {@link WriterOutputStream} pushes it to the underlying stream.
Note that while there are use cases where there is no alternative to using this class, very often the need to use this class is an indication of a flaw in the design of the code. This class is typically used in situations where an existing API only accepts an {@link OutputStream} object, but where the stream is known to representcharacter data that must be decoded for further use.
Instances of {@link WriterOutputStream} are not thread safe.
@see org.apache.commons.io.input.ReaderInputStream
@author Andreas Veithen
@since Commons IO 2.0