Java Reference
In-Depth Information
This loop reads the entire file referenced by
diskfile
one byte at a time and displays
each byte, followed by a space character. It also displays -1 when the end of the file is
reached; you could guard against this easily with an
if
statement.
The
ByteReader
application in Listing 15.1 uses a similar technique to read a file input
stream. The input stream's
close()
method is used to close the stream after the last byte
in the file is read. Always close streams when you no longer need them; it frees system
resources.
LISTING 15.1
The Full Text of
ByteReader.java
1: import java.io.*;
2:
3: public class ByteReader {
4: public static void main(String[] arguments) {
5: try {
6: FileInputStream file = new
7: FileInputStream(“class.dat”);
8: boolean eof = false;
9: int count = 0;
10: while (!eof) {
11: int input = file.read();
12: System.out.print(input + “ “);
13: if (input == -1)
14: eof = true;
15: else
16: count++;
17: }
18: file.close();
19: System.out.println(“\nBytes read: “ + count);
20: } catch (IOException e) {
21: System.out.println(“Error — “ + e.toString());
22: }
23: }
24: }
If you run this program, you'll get the following error message:
Error — java.io.FileNotFoundException: class.dat (The system
cannot find the file specified).
This error message looks like the kind of exception generated by the compiler, but it's
actually coming from the
catch
block in lines 20-22 of the
ByteReader
application. The
exception is being thrown by lines 6-7 because the
class.dat
file cannot be found.