Java Reference
In-Depth Information
Display 10.19
Binary File I/O of Objects (part 2 of 3)
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
}
45
catch (ClassNotFoundException e)
46
{
47
System.out.println("Problems with file input.");
48
}
49
catch (IOException e)
50
{
51
System.out.println("Problems with file input.");
52
}
Search WWH ::




Custom Search