Monday, 27 July 2009

The Buffer and the Stream

This might seem like the world's most banal post on serialization. It deals with the issue of how to write a Java object to a file (and the equally important task of reading it). However the use of the "oos" is not without its subtleties, mainly relating to the concepts of "flushing" and "draining". A "drain" of an "oos" is in some sense an incomplete "flush" of the self-same "oos".

String filePath = "/(directory)/MyClass.sel";
FileOutputStream fos = new FileOutputStream( filePath );
ObjectOutputStream oos = new ObjectOutputStream( fos );
oos.writeObject( instanceObject );
oos.close();

Also, we must be careful to catch any IOExceptions. writeObject writes the state of an object (readObject restores it). Incidentally, it is worth remarking that the above code has certain poetic qualities due to the repitition of "oos".

The "oos" can be flushed and it can also be drained. In the case of a flush, the command will write any buffered bytes and flush through to the underlying stream, in the case of a drain, the bytes are not flushed thru to underlying stream. In each case there are two actors, the buffer and the stream. The buffer is the boat that floats on the stream.

The "oos" also has specialist write methods e.g.

writeBoolean(boolean val)
writeByte(int val) - writes an 8 bit byte
writeShort(int val) - write 16 bit short
etc

No comments: