Java Reference
In-Depth Information
// Read the objects back from the file
System.out.println("\nReading objects from the file: ");
try {
ObjectInputStream objectIn =
new ObjectInputStream(
new BufferedInputStream (
new FileInputStream("C:/Beg Java Stuff/Polygons.bin")));
PolyLine theLine = (PolyLine)objectIn.readObject();
System.out.println(theLine); // Display the first object
theLine = (PolyLine)objectIn.readObject();
System.out.println(theLine); // Display the second object
objectIn.close(); // Close the input stream
} catch(ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
} catch(IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}
}
This produces the output:
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0) (0.0,0.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0) (0.0,0.0)
(10.0,10.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0) (0.0,0.0)
Reading objects from the file:
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0) (0.0,0.0)
(10.0,10.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0) (0.0,0.0)
How It Works
We create two different
PolyLine
objects in the same manner as in the original example and we
display them on standard output as before. We then create an
ObjectOutputStream
for the file,
Polygons.bin
, in the
C:\Beg
Java
Stuff
directory and write each of the
PolyLine
objects to the
file using the
writeObject()
method. You should adjust the file name and directory to suit your
environment if necessary. We then call the
close()
method to close the output stream. We don't need
to explicitly write the
LinkedList
and
Point
objects to the stream. These are part of the
PolyLine
object so they are taken care of automatically. The same goes for when we read the
PolyLine
objects
back. All the subsidiary objects are reconstructed automatically.
To read the file, we create an
ObjectInputStream
object for
Polygons.bin
. We then read the first
object using the
readObject()
method and store the reference to it in the variable
theObject
. We
then output the object,
read
, to the standard output stream. The same process is repeated for the
second
PolyLine
object. It couldn't be simpler really, could it?