Java Reference
In-Depth Information
PITFALL: A
RandomAccessFile
Need Not Start Empty
If a file already exists, then when it is opened with
RandomAccessFile
, the length is
not reset to
0
, but the file pointer will be positioned at the start of the file. So, old data
in the file is not lost and the file pointer is set for the most likely position for reading,
not the most likely position for writing.
Self-Test Exercises
44. If you run the program in Display 10.22 a second time, will the output be the same?
45. How can you modify the program in Display 10.22 so the file always starts out
empty?
Chapter Summary
•
Files that are considered to be strings of characters and that look like characters to
your program and your editor are called text files. Files whose contents must be
handled as strings of binary digits are called binary files.
•
You can use the class
PrintWriter
to write to a text file and can use the class
Scanner
or
BufferedReader
to read from a text file.
•
The class
File
can be used to check whether there is a file with a given name. It
can also check whether your program is allowed to read the file and/or allowed to
write to the file.
•
Your program can use the class
ObjectOutputStream
to write to a binary file and
can use the class
ObjectInputStream
to read from a binary file.
•
Your program can use the method
writeObject
of the class
ObjectOutputStream
to write class objects to a binary file. The objects can be read back with the
method
readObject
of the class
ObjectInputStream
.
•
To use the method
writeObject
of the class
ObjectOutputStream
or the method
readObject
of the class
ObjectInputStream
, the class whose objects are written to
a file must implement the
Serializable
interface.
•
The way that you test for the end of a file depends on whether your program is
reading from a text file or a binary file.
•
You can use the class
RandomAccessFile
to create a stream that gives random
access to the bytes in a file.