Java Reference
In-Depth Information
Listing 6-1. persistDVD Method Demonstrating FileOutputStream to Serialize a DVD Object
private boolean persistDVD(DVD dvd) throws IOException{
boolean retVal=false;
//open a FileIOutputStream associated with the data
//notice that if the DVD does not already exist,
//it will be created.
String filePath = dbName+"/"+ dvd.getUPC() + fileExtension;
FileOutputStream fos = new FileOutputStream(filePath);
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
//Read in the data from the object
oos.writeObject(dvd);
}
finally {
//close all references
oos.close();
fos.close();
}
}
Listing 6-2. retrieveDVD Method Demonstrating FileInputStream to Deserialize a DVD Object
private DVD retrieveDVD(String upc, String fileExtension) throws IOException,
ClassNotFoundException {
DVD retVal = null;
//get the path to the object's serialized state.
try {
String filePath = dbName+"/"+ upc + fileExtension;
FileInputStream fis = new FileInputStream(filePath);
//Read in the data from the object
ObjectInputStream ois = new ObjectInputStream(fis);
retVal = (DVD)ois.readObject();
}
finally {
ois.close();
fis.close();
}
return retVal;
}
Caution The code shown in these listings is not contained in the actual project since Denny's DVDs
relies on the JVM and the default serialization mechanism. The code is used as a pedagogical device to
illustrate how to explicitly serialize an object.
Search WWH ::




Custom Search