Java Reference
In-Depth Information
Sometimes, the order of the catch clauses matters. Suppose we want to catch “file not found” separately from all
other exceptions. We may be tempted to write this:
try {
Scanner in = new Scanner(new FileReader("input.txt"));
n = in.nextInt();
}
catch (Exception e) {
//code for all exceptions (except “file not found”, presumably)
}
catch (FileNotFoundException e) {
//code for file not found
}
This code would not even compile! When Java reaches the last catch , it will complain that
FileNotFoundException has already been caught. This is because FileNotFoundException is a subclass of Exception .
To fix the problem, we must put catch (FileNotFoundException e) before catch (Exception e) .
In general, subclass exceptions must come before the containing class.
7.6 Input/Output for Binary File
As mentioned earlier, a binary file contains data in a form that corresponds exactly with the internal representation of
the data. For example, if a float variable occupies 4 bytes of memory, writing it to a binary file simply involves making
an exact copy of the 4 bytes. On the other hand, writing it to a text file causes it to be converted to character form, and
the characters obtained are stored in the file.
Normally, a binary file can be created only from within a program, and its contents can be read only by a
program. Listing a binary file, for example, produces only “garbage” and, sometimes, generates an error. Compare a
text file that can be created by typing into it and whose contents can be listed and read by a human. However, a binary
file has the following advantages:
Data can be transferred to and from a binary file much faster than for a text file since no data
conversions are necessary; the data is read and written as is.
The values of data types such as arrays and structures can be written to a binary file. For a text
file, individual elements must be written.
Data stored in a binary file usually occupies less space than the same data stored in a text file.
For example, the integer -25367 (six characters) occupies 6 bytes in a text file but only 2 bytes
in a binary file.
7.6.1 DataOutputStream and DataInputStream
Consider the problem of reading integers from a text file, num.txt , and writing them, in their internal form, to a
(binary) file, num.bin . We assume that the numbers in num.txt are terminated by 0 and 0 is not to be written to the
binary file. This can be done with Program P7.2.
 
Search WWH ::




Custom Search