Java Reference
In-Depth Information
In the sample execution for the program in Fig. 15.10, we entered information for
five accounts—the same information shown in Fig. 15.5. The program does not show
how the data records actually appear in the file. Remember that now we're using
binary
files
, which are not humanly readable. To verify that the file has been created successfully,
the next section presents a program to read the file's contents.
The preceding section showed how to create a file for sequential access using object serial-
ization. In this section, we discuss how to
read serialized data
sequentially from a file.
The program in Fig. 15.11 reads records from a file created by the program in
Section 15.5.1 and displays the contents. The program opens the file for input by calling
Files
static
method
newInputStream
, which receives a
Path
specifying the file to open
and, if the file exists, returns an
InputStream
that can be used to read from the file. In
Fig. 15.10, we wrote objects to the file, using an
ObjectOutputStream
object. Data must
be read from the file in the same format in which it was written. Therefore, we use an
ObjectInputStream
wrapped
around an
InputStream
(lines 26-27). If no exceptions
occur when opening the file, variable
input
can be used to read objects from the file.
1
// Fig. 15.11: ReadSequentialFile.java
2
// Reading a file of objects sequentially with ObjectInputStream
3
// and displaying each record.
4
import
java.io.EOFException;
5
import
java.io.IOException;
6
7
import
java.io.ObjectInputStream;
import
java.nio.file.Files;
8
import
java.nio.file.Paths;
9
10
public class
ReadSequentialFile
11
{
12
private static
ObjectInputStream input;
13
14
public static void
main(String[] args)
15
{
16
openFile();
17
readRecords();
18
closeFile();
19
}
20
21
// enable user to select file to open
22
public static void
openFile()
23
{
24
try
// open file
25
{
26
input =
new
ObjectInputStream(
Files.newInputStream(Paths.get(
"clients.ser"
)));
27
28
}
29
catch
(IOException ioException)
30
{
Fig. 15.11
|
Reading a file of objects sequentially with
ObjectInputStream
and displaying
each record. (Part 1 of 3.)