The InputStreamReader Class
The most basic concrete subclass of Reader
is
InputStreamReader
:
public class InputStreamReader extends Reader
The constructor connects a character reader to an underlying input stream:
public InputStreamReader(InputStream in) public InputStreamReader(InputStream in, String encoding) throws UnsupportedEncodingException
The first constructor uses the platform’s default encoding, as
given by the system property file.encoding
. The
second one uses the specified encoding. For example, to attach an
InputStreamReader
to System.in
with the default encoding (generally ISO Latin-1):
InputStreamReader isr = new InputStreamReader(System.in);
If you want to read a file encoded in Latin-5 (ASCII plus Turkish, as specified by ISO 8859-9), you might do this:
FileInputStream fin = new FileInputStream("symbol.txt"); InputStreamReader isr = new InputStreamReader(fin, "8859_9");
There’s no easy way to determine which encodings are supported, but the ones listed in Table 2.4 are supported by most VMs.
The read()
methods read bytes from an underlying
input stream and convert those bytes to characters according to the
specified encoding:
public int read() throws IOException public int read(char c[], int off, int length) throws IOException
The getEncoding()
method returns a string
containing the name of the encoding used by this reader:
public String getEncoding()
The remaining two methods just override methods from
java.io.Reader
but behave identically from the perspective of the programmer: ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.