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.

}<br />

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

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

}<br />

int numRead = 0;<br />

for (int i = offset; i < offset+length; i++) {<br />

int temp = this.read();<br />

if (temp == -1) break;<br />

text[i] = (char) temp;<br />

numRead++;<br />

}<br />

return numRead;<br />

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

}<br />

char[] c = new char[(int) n];<br />

int numSkipped = this.read(c);<br />

return numSkipped;<br />

15.11.2 The FilterWriter Class<br />

The FilterWriter class has a single constructor and no other unique methods:<br />

protected FilterWriter(Writer out)<br />

The out argument is the writer to which this filter is chained. This reference is stored in a<br />

protected field called out, to which text sent through this filter is written.<br />

protected Writer out<br />

Since FilterWriter is an abstract class, only subclasses may be instantiated. Therefore, it<br />

doesn't matter that the constructor is protected, since it may only be invoked from subclass<br />

constructors anyway. FilterWriter provides the usual collection of write(), close(), and<br />

flush() methods:<br />

public void write(int c) throws <strong>IO</strong>Exception<br />

public void write(char[] text, int offset, int length) throws <strong>IO</strong>Exception<br />

public void write(String s, int offset, int length) throws <strong>IO</strong>Exception<br />

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

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

These all simply invoke the equivalent method in the out field with the same arguments. For<br />

example:<br />

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

out.close();<br />

}<br />

In general, each subclass will have to override at least the three write() methods to perform<br />

the filtering.<br />

There are no subclasses of FilterWriter in the core API. Example 15.8, SourceWriter, is<br />

an example of a FilterWriter that converts Unicode text to \u-escaped ASCII. The big<br />

384

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

Saved successfully!

Ooh no, something went wrong!