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 />

These methods behave like any other reader's read() methods. If the end of the array is<br />

reached, they return -1.<br />

The skip() method skips chars in the buf array by advancing pos without actually returning<br />

any characters:<br />

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

The ready() method returns true if pos is less than count; that is, if any unread characters<br />

remain in the array:<br />

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

CharArrayReaders support marking and resetting to the limit of the length of the array.<br />

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

markedPos equal to pos. The readAheadLimit argument is for compatibility; its value is<br />

ignored. The reset() method sets pos equal to markedPos.<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 buf to null. Attempts to read from a CharArrayReader<br />

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

public void close()<br />

15.6 String Readers and Writers<br />

The java.io.StringReader and java.io.StringWriter classes allow programmers to use<br />

Reader and Writer methods to read and write strings. Like char arrays, <strong>Java</strong> strings are also<br />

composed of pure Unicode characters. Therefore, they're good sources of data for readers and<br />

good targets for writers. This is the other common case where readers and writers don't need<br />

to convert between different encodings.<br />

15.6.1 String Writers<br />

This class would more accurately be called StringBufferWriter, but StringWriter is more<br />

poetic. A StringWriter maintains an internal java.lang.StringBuffer object to which<br />

written characters are appended. This buffer can easily be converted to a string as necessary.<br />

public class StringWriter extends Writer<br />

There is a single public constructor:<br />

public StringWriter()<br />

There is also a constructor that allows you to specify the initial size of the internal string<br />

buffer. This isn't too important, because string buffers (and, by extension, string writers) are<br />

expanded as necessary. Still, if you can estimate the size of the string in advance, it's<br />

369

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

Saved successfully!

Ooh no, something went wrong!