Home Segments Top Top Previous Next

636: Mainline

Conveniently, Java's Vector class implements the Serializable interface. Thus, inasmuch as the Movie class, defined in Segment 634, also implements the Serializable interface, you can use writeObject and readObject to write entire vectors of movies serially and to read them back serially, as shown in the following demonstration program. The readData method defined in Segment 613 provides the initial vector of Movie instances from a text file:

import java.io.*; 
import java.util.*; 
public class Demonstrate { 
 public static void main(String argv[])  
  throws IOException, ClassNotFoundException { 
  // Read from text file: 
  Vector mainVector = Auxiliaries.readMovieFile("input.data");  
  // Write out vector of Movie instances: 
  FileOutputStream fileOutputStream 
   = new FileOutputStream("transit.data"); 
  ObjectOutputStream objectOutputStream  
   = new ObjectOutputStream(fileOutputStream); 
  objectOutputStream.writeObject(mainVector); 
  objectOutputStream.close(); 
  // Read in vector of Movie instances: 
  FileInputStream fileInputStream 
    = new FileInputStream("transit.data");  
  ObjectInputStream objectInputStream 
    = new ObjectInputStream(fileInputStream); 
  mainVector = (Vector) objectInputStream.readObject(); 
  // Test vector: 
  for (Iterator i = mainVector.iterator(); i.hasNext();) {  
   System.out.println(((Movie) i.next()).rating());  
}}}