Java Reference
In-Depth Information
In addition to the possibility of an IOException being generated during I/O, there
is also the possibility of a ClassNotFoundException being generated, so we must
either handle this exception ourselves or throw it. A further consideration that needs
to be made is how we detect end-of-fi le, since there is no equivalent of the Scanner
class's hasNext method for use with object streams. We could simply use a for
loop to read back the number of objects we believe that the fi le holds, but this would
be very bad practice in general (especially as we may often not know how many
objects a particular fi le holds).
The only viable option there appears to be is to catch the EOFException that is
generated when we read past the end of the fi le. This author feels rather uneasy
about having to use this technique, since it confl icts with the fundamental ethos of
exception handling. Exception handling (as the term implies) is designed to cater
for exceptional and erroneous situations that we do not expect to happen if all goes
well and processing proceeds as planned. Here, however, we are going to be using
exception handling to detect something that we not only know will happen eventu-
ally, but also are dependent upon happening if processing is to reach a successful
conclusion. Unfortunately, there does not appear to be any alternative to this
This example creates three objects of a class called Personnel and writes them to
disc fi le (as objects). It then reads the three objects back from fi le (employing a
typecast to convert them into their original type) and makes use of the 'get' methods
of class Personnel to display the data members of the three objects. We must, of
course, ensure that class Personnel implements the Serializable interface (which
involves nothing more than including the phrase implements Serializable ). In a real-
life application, class Personnel would be defi ned in a separate fi le, but it has been
included in the main application fi le below simply for convenience.
public class Serialise
public static void main(String[] args)
throws IOException, ClassNotFoundException
ObjectOutputStream outStream =
new ObjectOutputStream(
new FileOutputStream("personnel.dat"));
Personnel[] staff =
{new Personnel(123456,"Smith", "John"),
new Personnel(234567,"Jones", "Sally Ann"),
new Personnel(999999,"Black", "James Paul")};
for (int i=0; i<staff.length; i++)
Search WWH ::

Custom Search