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.

public StreamedTextArea(String text, int rows, int columns) {<br />

this(text, rows, columns, SCROLLBARS_BOTH);<br />

}<br />

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

public StreamedTextArea(String text, int rows, int columns, int<br />

scrollbars) {<br />

super(text, rows, columns, scrollbars);<br />

setEditable(false);<br />

}<br />

}<br />

public OutputStream getOutputStream() {<br />

return theOutput;<br />

}<br />

class TextAreaOutputStream extends OutputStream {<br />

}<br />

public synchronized void write(int b) {<br />

// recall that the int should really just be a byte<br />

b &= 0x000000FF;<br />

}<br />

// must convert byte to a char in order to append it<br />

char c = (char) b;<br />

append(String.valueOf(c));<br />

public synchronized void write(byte[] data, int offset, int length) {<br />

append(new String(data, offset, length));<br />

}<br />

The TextAreaOutputStream inner class is quite simple. It extends OutputStream and thus<br />

must implement the abstract method write(). It also overrides the primary array write()<br />

method to provide a more efficient implementation. To use this class, you simply add an<br />

instance of it to a container like an applet or a window, much as you'd add a regular text area.<br />

Next you invoke its getOutputStream() method to get a reference to the output stream for<br />

the area, then use the usual write() methods to write into the text area. Often these steps will<br />

take place at different times in different methods.<br />

Figure 2.1 shows a program using a StreamedTextArea to display data downloaded from<br />

http://www.oreilly.com/. The application in this picture will be developed in Chapter 5.<br />

40

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

Saved successfully!

Ooh no, something went wrong!