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.

}<br />

public void actionPerformed(ActionEvent evt) {<br />

}<br />

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

try {<br />

URL u = new URL(theURL.getText());<br />

InputStream in = u.openStream();<br />

OutputStream out = theDisplay.getOutputStream();<br />

StreamCopier.copy(in, out);<br />

in.close();<br />

out.close();<br />

}<br />

catch (MalformedURLException ex) {theDisplay.setText("Invalid URL");}<br />

catch (<strong>IO</strong>Exception ex) {theDisplay.setText("Invalid URL");}<br />

public void windowClosing(WindowEvent e) {<br />

}<br />

this.setVisible(false);<br />

this.dispose();<br />

public void windowOpened(WindowEvent e) {}<br />

public void windowClosed(WindowEvent e) {}<br />

public void windowIconified(WindowEvent e) {}<br />

public void windowDeiconified(WindowEvent e) {}<br />

public void windowActivated(WindowEvent e) {}<br />

public void windowDeactivated(WindowEvent e) {}<br />

public static void main(String args[]) {<br />

}<br />

URLViewer me = new URLViewer();<br />

me.init();<br />

The URLViewer class itself extends Frame. An alternative would have been to extend Panel,<br />

which would have allowed URLViewer objects to be embedded in other containers. However,<br />

this application seemed big enough to justify exclusive use of a window. URLViewer<br />

implements the WindowListener interface to enable the user to close the window by clicking<br />

in the close box. Only the windowClosing() method is nontrivial. The other six window<br />

methods are do-nothing methods required to satisfy the contract of the WindowListener<br />

interface.<br />

The init() method builds the interface and displays the window. This is invoked by the<br />

main() method, which constructs a new URLViewer object. The constructor is quite simple,<br />

merely passing the title of the frame to the superclass constructor.<br />

The streamed text area is filled when the user clicks the Load button or hits Return inside the<br />

URL text field. The URLViewer object listens to both of these components. The URLViewer's<br />

actionPerformed() method constructs a URL from the text in the text field, then opens an<br />

input stream from the URL in the text field. Next, StreamCopier from Chapter 3 pours the<br />

data from the URL's input stream into the text area's output stream. When that's finished, both<br />

streams are closed.<br />

73

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

Saved successfully!

Ooh no, something went wrong!