Java Reference
In-Depth Information
MyClass theObject = null; // Store the object here
try {
theObject = (MyClass)(objectIn.readObject());
} catch(ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
To deserialize the object, we call the method readObject() and cast the reference returned to the
type MyClass .
Armed with the knowledge of how the readObject() method works, we can now read the file that we
wrote in the previous example.
Try It Out - Deserializing Objects
We can read the file containing Junk objects with the following code:
import java.io.*;
class DeserializeObjects {
public static void main(String args[]) {
ObjectInputStream objectIn = null; // Stores the stream reference
int objectCount = 0; // Number of objects read
Junk object = null; // Stores an object reference
try {
objectIn = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream("C:/Beg Java Stuff/JunkObjects.bin")));
// Read from the stream until we hit the end
while(true) {
object = (Junk)objectIn.readObject(); // Read an object
objectCount++; // Increment the count
System.out.println(object); // Output the object
}
} catch(ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
} catch(EOFException e) // This will execute when we reach EOF {
System.out.println("EOF reached. "+ objectCount + " objects read.");
} catch(IOException e) // This is for other I/O errors {
e.printStackTrace(System.err);
System.exit(1);
Search WWH ::




Custom Search