Next: None. Up: Binary files. Previous: The DataOutputStream class.


Writing objects to files

Textbook: Section 14.7

You'll notice that I didn't include any methods for writing entire objects into a binary file. There are two other classes that provide this capability: ObjectOutputStream and ObjectInputStream. They're analogous to DataOutputStream and DataInputStream - even providing the same methods. But each adds a new method: ObjectOutputStream provides the method

void writeObject(Object obj)
Writes a binary representation of the object obj.

and ObjectInputStream provides the method
Object readObject()
Reads a binary representation of an object and returns it.

In order to store an object in a file, Java will store the name of a class, followed by a list of the binary values of any instance variables for the object. Then, to read the object, it reads the name of a class, allocates memory to accomodate it, and then initializes its instance variables according to the following binary values.

It's already pretty complicated - this isn't the sort of thing you'd want to implement (or even that you could implement, without using some additional features of Java that we haven't discussed). But it gets more complex: The problem is that some instance variables could be pointing to objects. Simply writing out the memory address of these objects into the file is no good, since the memory address won't be same when we later read the object in a separate process.

Java has a nifty (and complex) technique for handling this called serialization. Serialization allows you to specify for an object that, when it is written into a file, it should also be sure to write any objects to which any of its instance variables points into the file also. (Moreover, some of these objects may require writing more objects into the file.)

But it gets even more complex: Often you have multiple pointers to the same object, and you need to make sure that when written, the multiple pointers still point to the same object. (As an example of when this would occur, suppose in our Very Small Video program wanted to save its entire database into a file. You could write the Store object into a file. If a Customer has a video checked out, that Customer would point to a Video, but it's important that the Store also point to the same Video. Otherwise, when the Customer checks the video back in, the Video pointed to by the Store would still display that the video is still unavailable.) Serialization handles this issue, too, but handling it gets pretty complex.

I'm only mentioning serialization in case some day in the remote future the issue pops up, and perhaps you might remember me saying something about serialization, and then you can look up how to do it. It's not something we'll be covering in class beyond the rough idea of what it is.


Next: None. Up: Binary files. Previous: The DataOutputStream class.