Java Reference
In-Depth Information
PITFALL: Mixing Class Types in the Same File
The best way to write and read objects using ObjectOutputStream and
ObjectInputStream is to store only data of one class type in any one file. If you store
objects of multiple class types or even objects of only one class type mixed in with
primitive type data, it has been our experience that the system can get confused and
you could lose data.
Array Objects in Binary Files
An array is an object and hence a suitable argument for writeObject . An entire array
can be saved to a binary file using writeObject and later read using readObject .
When doing so, if the array has a base type that is a class, then the class must be
serializable. This means that if you store all your data for one serializable class in a
single array, then you can output all your data to a binary file with one invocation of
writeObject .
This way of storing an array in a binary file is illustrated in Display 10.20. Note
that the base class type, SomeClass , is serializable. Also, notice the type cast that uses
the array type SomeClass[] . Because readObject returns its value as an object of type
Object , it must be type cast to the correct array type.
Self-Test Exercises
40. How do you make a class implement the Serializable interface?
41. What import statement do you need to be able to use the Serializable
interface?
42. What is the return type for the method readObject of the class
ObjectInputStream ?
43.
Is an array of type Object ?
Display 10.20
File I/O of an Array Object (part 1 of 3)
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 public class ArrayIODemo
8 {
9 public static void main(String[] args)
 
Search WWH ::




Custom Search