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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

Since string objects are immutable, the data in the string may not be changed after the<br />

StringReader is constructed. The current position from which characters are read is stored in<br />

a private field. Synchronization and thread safety are thus not major problems for this class.<br />

Of course, the class has the usual read() methods, all of which read as many characters as<br />

requested from the string:<br />

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

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

These methods return -1 if the end of the string has been reached. They throw an<br />

<strong>IO</strong>Exception if the reader has been closed.<br />

The skip() method skips forward in the string the specified number of places and returns the<br />

number of characters skipped. It throws an <strong>IO</strong>Exception if the reader is closed.<br />

public long skip(long n) throws <strong>IO</strong>Exception<br />

The ready() method returns true. Strings are always ready to be read.<br />

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

String readers support marking and resetting to the limit of the string's length.<br />

markSupported() returns true. mark() marks the current position in the stream. (The<br />

readAheadLimit argument is for compatibility only; its value is ignored.) The reset()<br />

method moves backward in the string to the marked position.<br />

public boolean markSupported()<br />

public void mark(int readAheadLimit) throws <strong>IO</strong>Exception<br />

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

Finally, the close() method sets the internal string data to null. Attempts to read from a<br />

StringReader after it's been closed throw <strong>IO</strong>Exceptions.<br />

public void close()<br />

Here's a simple method that uses StringReader to break a string into its separate characters<br />

and print them:<br />

public static void printCharacters(String s) {<br />

}<br />

StringReader sr = new StringReader(s);<br />

try {<br />

int c;<br />

while ((c = sr.read()) != -1) {<br />

System.out.println((char) c);<br />

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

return;<br />

371

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

Saved successfully!

Ooh no, something went wrong!