Page 660 - Introduction to Programming with Java: A Problem Solving Approach
P. 660

                626 Chapter 15 Files
the same as a previously instantiated String. This is a nice space-saving feature, but it can be a problem if you’re simulating the behavior of a particular object, and you want a file to accumulate a record of that object’s changing state as the simulation progresses. To see this problem, replace the writeObject state- ment in Figure 15.11’s WriteObject program with these three statements:
fileOut.writeObject(testObject);
testObject.number *= 1.1;
fileOut.writeObject(testObject);
Then execute the revised WriteObject program and the ReadObject program, and this is what you’ll get:
Enter filename:
objectFile.data
1 test 2.0
1 test 2.0
The second record of the object’s state is just a copy of the first record. It doesn’t reflect the change in the value of the number variable. To make Java store the latest state of an object instead of just a reference to the original state, you need to invoke ObjectOutputStream’s reset method sometime before you output the updated version of the object. To see how this works, replace the above three statements with these four statements:
fileOut.writeObject(testObject);
    fileOut.reset();
testObject.number *= 1.1;
fileOut.writeObject(testObject);
Then execute the revised WriteObject program and the ReadObject program, and you’ll get the result you want:
Enter filename:
objectFile.data
Apago PDF Enhancer
1 test 2.0
1 test 2.2
15.9 The File Class
This section describes the File class. It’s different from the other classes in this chapter in that it doesn’t deal with a file’s contents. It deals with the file itself, and it describes the file’s environment—where the file is in the computer.
Instantiating a File Object
To use the File class, you first need to instantiate an object that represents a file. Here’s the API heading
for the File constructor:
public File(String filename)
For example, to instantiate a File object for a file named dalaiLamaEssay.doc, do this: File paper = new File("daliLamaEssay.doc");
This allows an updated version of the same object to be output.
 





































































   658   659   660   661   662