Page 659 - Introduction to Programming with Java: A Problem Solving Approach
P. 659
15.8 Object File I/O 625
/**************************************************************
*
ReadObject.java
Dean & Dean
This reads two objects from a binary file.
**************************************************************/
*
*
*
import java.io.*;
import java.util.Scanner;
public class ReadObject
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
ObjectInputStream fileIn = null;
TestObject testObject;
System.out.print("Enter filename: ");
try
{⎫ fileIn = new ObjectInputStream( ⎬
new FileInputStream(stdIn.nextLine())); ⎭ testObjectAp= a(TgesotObjPecDt)FfilEenInh.raeandOcbjecrt(); testObject.display();
testObject = (TestObject) fileIn.readObject(); testObject.display();
Open the file.
}
// end ReadObject class
}
// end main
}
{
}
}
Sample session:
fileIn.close();
Close the file.
catch (IOException e)
System.out.println("IO Error: " + e.getMessage());
catch (ClassNotFoundException e)
{
System.out.println("ClassNotFound " + e.getMessage());
Enter filename: objectFile.data
1
test 2.0
IO Error: null
Read objects from the file.
Figure 15.12 ReadObject program that tries to read two objects from a file