23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

15.4 The InputStreamReader Class<br />

The most basic concrete subclass of Reader is InputStreamReader:<br />

public class InputStreamReader extends Reader<br />

The constructor connects a character reader to an underlying input stream:<br />

public InputStreamReader(InputStream in)<br />

public InputStreamReader(InputStream in, String encoding)<br />

throws UnsupportedEncodingException<br />

<strong>Java</strong> I/O<br />

The first constructor uses the platform's default encoding, as given by the system property<br />

file.encoding. The second one uses the specified encoding. For example, to attach an<br />

InputStreamReader to System.in with the default encoding (generally ISO Latin-1):<br />

InputStreamReader isr = new InputStreamReader(System.in);<br />

If you want to read a file encoded in Latin-5 (ASCII plus Turkish, as specified by ISO 8859-<br />

9), you might do this:<br />

FileInputStream fin = new FileInputStream("symbol.txt");<br />

InputStreamReader isr = new InputStreamReader(fin, "8859_9");<br />

There's no easy way to determine which encodings are supported, but the ones listed in Table<br />

B.4 are supported by most VMs.<br />

The read() methods read bytes from an underlying input stream and convert those bytes to<br />

characters according to the specified encoding:<br />

public int read() throws <strong>IO</strong>Exception<br />

public int read(char c[], int off, int length) throws <strong>IO</strong>Exception<br />

The getEncoding() method returns a string containing the name of the encoding used by this<br />

reader:<br />

public String getEncoding()<br />

The remaining two methods just override methods from java.io.Reader but behave<br />

identically from the perspective of the programmer:<br />

public boolean ready() throws <strong>IO</strong>Exception<br />

public void close() throws <strong>IO</strong>Exception<br />

Example 15.2 uses an InputStreamReader to read a file in a user-specified encoding. The<br />

FileConverter reads the name of the input file, the name of the of the output file, the input<br />

encoding, and the output encoding. Characters that are not available in the output character set<br />

are replaced by the substitution character, generally the question mark.<br />

365

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!