Class ReaderInputStream

All Implemented Interfaces:
Closeable, AutoCloseable

public class ReaderInputStream extends InputStream
InputStream implementation that reads a character stream from a Reader and transforms it to a byte stream using a specified charset encoding. The stream is transformed using a CharsetEncoder object, guaranteeing that all charset encodings supported by the JRE are handled correctly. In particular for charsets such as UTF-16, the implementation ensures that one and only one byte order marker is produced.

Since in general it is not possible to predict the number of characters to be read from the Reader to satisfy a read request on the ReaderInputStream, all reads from the Reader are buffered. There is therefore no well defined correlation between the current position of the Reader and that of the ReaderInputStream. This also implies that in general there is no need to wrap the underlying Reader in a BufferedReader.

ReaderInputStream implements the inverse transformation of InputStreamReader; in the following example, reading from in2 would return the same byte sequence as reading from in (provided that the initial byte sequence is legal with respect to the charset encoding):

To build an instance, use ReaderInputStream.Builder.

 InputStream inputStream = ...
 Charset cs = ...
 InputStreamReader reader = new InputStreamReader(inputStream, cs);
 ReaderInputStream in2 = ReaderInputStream.builder()

ReaderInputStream implements the same transformation as OutputStreamWriter, except that the control flow is reversed: both classes transform a character stream into a byte stream, but OutputStreamWriter pushes data to the underlying stream, while ReaderInputStream pulls it from 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 InputStream, but where the most natural way to produce the data is as a character stream, i.e. by providing a Reader instance. An example of a situation where this problem may appear is when implementing the javax.activation.DataSource interface from the Java Activation Framework.

The InputStream.available() method of this class always returns 0. The methods InputStream.mark(int) and InputStream.reset() are not supported.

Instances of ReaderInputStream are not thread safe.

See Also: