Java Reference
In-Depth Information
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[] . Since 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)
10
{
11
SomeClass[] a = new SomeClass[2];
12
a[0] = new SomeClass(1, 'A');
13
a[1] = new SomeClass(2, 'B');
14
try
15
{
16
ObjectOutputStream outputStream =
17
new ObjectOutputStream( new FileOutputStream("arrayfile"));
18
outputStream.writeObject(a);
19
outputStream.close();
20
}
Search WWH ::




Custom Search