Java Reference
In-Depth Information
Caution
You have to read data in the same order and format in which they are stored. For exam-
ple, since names are written in UTF-8 using
writeUTF
, you must read names using
readUTF
.
Detecting the End of a File
If you keep reading data at the end of an
InputStream
, an
EOFException
will occur. This
exception can be used to detect the end of a file, as shown in Listing 19.3.
EOFException
L
ISTING
19.3
DetectEndOfFile.java
1
import
java.io.*;
2
3
public class
DetectEndOfFile {
4
public static void
main(String[] args) {
5
try
{
6 DataOutputStream output =
7
new
DataOutputStream(
new
FileOutputStream(
"test.dat"
));
8 output.writeDouble(
4.5
);
9 output.writeDouble(
43.25
);
10 output.writeDouble(
3.2
);
11 output.close();
12
13 DataInputStream input =
14
new
DataInputStream(
new
FileInputStream(
"test.dat"
));
15
while
(
true
) {
16 System.out.println(
output stream
output
close stream
input stream
input.readDouble()
);
input
17 }
18 }
19
20 System.out.println(
"All data were read"
);
21 }
22
catch
(IOException ex) {
23 ex.printStackTrace();
24 }
25 }
26 }
catch
(EOFException ex) {
EOFException
4.5
43.25
3.2
All data were read
The program writes three double values to the file using
DataOutputStream
(lines 6-10),
and reads the data using
DataInputStream
(lines 13-14). When reading past the end of the
file, an
EOFException
is thrown. The exception is caught in line 19.
19.4.4
BufferedInputStream
/
BufferedOutputStream
BufferedInputStream
/
BufferedOutputStream
can be used to speed up input and output
by reducing the number of disk reads and writes. Using
BufferedInputStream
, the whole
block of data on the disk is read into the buffer in the memory once. The individual data are
then delivered to your program from the buffer, as shown in Figure 19.11a. Using
BufferedOutputStream
, the individual data are first written to the buffer in the memory. When
the buffer is full, all data in the buffer is written to the disk once, as shown in Figure 19.11b.