Java Reference
In-Depth Information
outputs the bytes to an output stream. You can view DataInputStream / FileInputStream
and DataOutputStream / FileOutputStream working in a pipe line as shown in
Figure 17.11.
DataInputStream
FileInputStream
External File
int, double, string …
01000110011 …
DataOutputStream
FileOutputStream
External File
int, double, string …
01000110011 …
F IGURE 17.11
DataInputStream filters an input stream of byte to data and
DataOutputStream converts data into a stream of bytes.
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 17.3.
EOFException
L ISTING 17.3
DetectEndOfFile.java
1 import java.io.*;
2
3 public class DetectEndOfFile {
4 public static void main(String[] args) {
5 try {
6 try (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 }
12
13 try (DataInputStream input =
14 new DataInputStream( new FileInputStream( "test.dat" ))) {
15 while ( true )
16 System.out.println(input.readDouble());
17 }
18 }
19 catch (EOFException ex) {
20 System.out.println( "All data were read" );
21 }
22 catch (IOException ex) {
23 ex.printStackTrace();
24 }
25 }
26 }
output stream
output
input stream
input
EOFException
 
 
Search WWH ::




Custom Search