Java Reference
In-Depth Information
Display 10.16
Reading from a Binary File
1
import
java.io.ObjectInputStream;
2
import
java.io.FileInputStream;
3
import
java.io.IOException;
4
import
java.io.FileNotFoundException;
5
public class
BinaryInputDemo
6 {
7
public static void
main(String[] args)
8 {
9
try
10 {
11 ObjectInputStream inputStream =
12
new
ObjectInputStream(
new
FileInputStream("numbers.dat"));
13 System.out.println("Reading the file numbers.dat.");
14
int
n1 = inputStream.readInt();
15
int
n2 = inputStream.readInt();
16 System.out.println("Numbers read from file:");
17 System.out.println(n1);
18 System.out.println(n2);
19 inputStream.close();
20 }
21
catch
(FileNotFoundException e)
22 {
23 System.out.println("Cannot find file numbers.dat.");
24 }
25
catch
(IOException e)
26 {
27 System.out.println("Problems with input from numbers.dat.");
28 }
29 System.out.println("End of program.");
30 }
31 }
Sample Dialogue
Reading the file numbers.dat.
Numbers read from file:
0
1
End of program.
Assumes the program in
Display 10.13 was run to
create the file
numbers.dat
.