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

When you call read(), you also have to catch the <strong>IO</strong>Exception that it might throw. As I've<br />

observed, input and output are often subject to problems outside of your control: disks fail,<br />

network cables break, and so on. Therefore, virtually any I/O method can throw an<br />

<strong>IO</strong>Exception, and read() is no exception. You don't get an <strong>IO</strong>Exception if read()<br />

encounters the end of the input stream; in this case, it returns -1. You use this as a flag to<br />

watch for the end of stream. The following code shows how to catch the <strong>IO</strong>Exception and<br />

test for the end of the stream:<br />

try {<br />

int[] data = new int[10];<br />

for (int i = 0; i < data.length; i++) {<br />

int datum = System.in.read();<br />

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

data[i] = datum;<br />

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println("Couldn't read from<br />

System.in!");}<br />

The read() method waits or blocks until a byte of data is available and ready to be read.<br />

Input and output can be slow, so if your program is doing anything else of importance, you<br />

should try to put I/O in its own thread.<br />

read() is declared abstract; therefore, InputStream is abstract. Hence, you can never<br />

instantiate an InputStream directly; you always work with one of its concrete subclasses.<br />

Example 3.1 is a program that reads data from System.in and prints the numeric value of<br />

each byte read on the console using System.out.println(). This program could have been<br />

written more simply; in particular, I could have put all the logic in the main() method without<br />

any trouble. However, this example is the basis for a file-dumping utility that I'll develop<br />

throughout the book, and, therefore, I want a flexible design from the start.<br />

Example 3.1. The StreamPrinter Class<br />

package com.macfaq.io;<br />

import java.io.*;<br />

public class StreamPrinter {<br />

InputStream theInput;<br />

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

StreamPrinter sr = new StreamPrinter(System.in);<br />

sr.print();<br />

}<br />

public StreamPrinter(InputStream in) {<br />

theInput = in;<br />

}<br />

43

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

Saved successfully!

Ooh no, something went wrong!