Java Reference
In-Depth Information
Display 10.19
Binary File I/O of Objects
(part 1 of 2)
1
import
java.io.ObjectOutputStream;
2
import
java.io.FileOutputStream;
3
import
java.io.ObjectInputStream;
4
import
java.io.FileInputStream;
5
import
java.io.IOException;
6
import
java.io.FileNotFoundException;
7 /**
8
Demonstrates binary file I/O of serializable class objects.
9 */
10
public class
ObjectIODemo
11 {
12
public static void
main(String[] args)
13 {
14
try
15 {
16 ObjectOutputStream outputStream =
17
new
ObjectOutputStream(
new
FileOutputStream("datafile"));
18 SomeClass oneObject =
new
SomeClass(1, 'A');
19 SomeClass anotherObject =
new
SomeClass(42, 'Z');
20 outputStream.writeObject(oneObject);
21 outputStream.writeObject(anotherObject);
22 outputStream.close();
23 System.out.println("Data sent to file.");
24 }
25
catch
(IOException e)
26 {
27 System.out.println("Problem with file output.");
28
}
29 System.out.println(
30 "Now let's reopen the file and display the data.");
31
try
32 {
33 ObjectInputStream inputStream =
34
new
ObjectInputStream(
new
FileInputStream("datafile"));
Notice the type casts.
35 SomeClass readOne = (SomeClass)inputStream.readObject( );
36 SomeClass readTwo = (SomeClass)inputStream.readObject( );
37 System.out.println("The following were read from the file:");
38 System.out.println(readOne);
39 System.out.println(readTwo);
40 }
41
catch
(FileNotFoundException e)
42 {
43 System.out.println("Cannot find datafile.");
44
}