Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com

Essence OUT.

Essence IN.

We use a java.io.FileOutputStream, wrapped in a java.io.DataOutputStream ....

and we use some of DataOutputStream's convenient write methods .

Crucial is, that READING always has to be done IN THE SAME ORDER AS WRITING has taken place, and read methods have to be used, that correspond exactly to the write methods that have been used.

Major problems arise, if you don't adhere to this !

Smart thing to do would be, to create a record class that can save and retrieve itself.

In a real-life application, the file would contain much more data.

To retrieve all data, a loop is used :

As soon as a read method fails because there's nothing more to read, there's a jump out of the loop to this catch :

=========

NOTES

=========

Reader and Writer classes are CHARACTER-oriented and Stream classes are BYTE-oriented.

Stream classes are also SEQUENTIAL.

=========

DataOutputStream has all sorts of write methods :
writeBoolean
writeByte
writeBytes
writeChar
writeChars
writeFloat
writeLong
writeShort

Because in Java data types have a fixed length, you can rest assured, that using writeFloat, for instance, will always cause 4 bytes to be written to the stream. writeShort, always 2 bytes, etc.

DataInputStream has corresponding read methods, of course.

=========

writeUTF is an efficient String writing method, it writes the length of the String, followed by as many bytes are needed. For the Western character set, one byte per character suffices.