Page 658 - Introduction to Programming with Java: A Problem Solving Approach
P. 658
624 Chapter 15 Files
/***************************************************************
*
WriteObject.java
Dean & Dean
This writes an object to a binary file.
***************************************************************/
*
*
*
import java.io.*;
import java.util.Scanner;
public class WriteObject
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
ObjectOutputStream fileOut;
TestObject testObject = new TestObject(1, "test", 2.0);
String filename;
System.out.print("Enter filename: ");
filename = stdIn.nextLine();
try
{
Open the file.
fileOut = new AObpjeactgOuotputPStDreFam(En⎫⎬hancer new FileOutputStream(filename)); ⎭
fileOut.writeObject(testObject);
}
// end WriteObject class
}
// end main
fileOut.close();
// end try
catch (IOException e)
Close the file.
}
{
}
Sample session:
System.out.println("Error: " + e.getMessage());
Enter filename: objectFile.data
Write an object to the file.
Figure 15.11 WriteObject program that writes a Serializable object to a file
in the container object, and each primitive data item in all component objects in that container object, and
so on, down the composition tree to all the primitive leaves.
Outputting an Updated Version of a Previously Output Object
If you ask ObjectOutputStream’s writeObject method to output exactly the same object again while the file is still open, the serializing software recognizes the repetition and outputs just a reference to the previously output object. This is like what happens when you instantiate a new String that is exactly