Page 655 - Introduction to Programming with Java: A Problem Solving Approach
P. 655
The following code fragment shows what you might see in a program that reads data from a binary file having the above organization. After opening the file for binary input, the code stores the first block’s char- acters into a StringBuffer called table. (The API StringBuffer class implements a flexible kind of String.) Notice how the while loop condition looks for a null character that signals the end of the incoming stream of characters. After the character-reading operation terminates, the code reads the second block’s integer and stores it in an int called numRecords. Finally, the code instantiates Record objects to hold the pairs of values in the sub-blocks, and it adds those objects to an ArrayList called table.
Scanner stdIn = new Scanner(System.in);
DataInputStream fileIn;
char ch = 0;
int numRecords = 0;
ArrayList<Record> table = new ArrayList<Record>();
StringBuffer tableName = new StringBuffer();
a flexible “array”
15.7 Binary File I/O 621
System.out.print("Enter filename: ");
try
{
fileIn = new DataInputStream(new FileInputStream(
stdIn.nextLine()));
while((ch = fileIn.readChar()) != 0)
}
// end try
...
{
Apago PDF Enh
numRecords = fileIn.readInt();
for (int i=0; i<numRecords; i++)
a flexible “string”
}
tableName = tableName.append(ch);
{
Accumulate objects in an ArrayList. fileIn.readInt(), fileIn.readDouble()));
}
table.add(new Record(
fileIn.close();
A StringBuffer is more flexible than a String because it has append and insert methods that append to the end or insert anywhere in the middle. The above code uses the append method to ac- cumulate characters as they stream in from the file. Of course, StringBuffer also has a toString method which allows you to convert a StringBuffer into a String at any later time.
The argument of the Record constructor in the table.add method call near the end of this example tells how each object’s instance-variable values are arranged in the file. They are lined up in a sequence, one after another. Notice that our file-reading code had to know the basic file-formatting scheme ahead of time, but some of the file-format detail—the number of records the file contained—is embedded in the file itself. The file-reading code determines this formatting detail at the very last instant, as the data streams in. This combination of a standard protocol (formal agreement on how something should be done) plus an embed- ded variation is typical of formatting in real-world binary files. The difference is that real-world protocols and their embedded variations are a hundred times more complicated than our simple example. Program- mers often employ some kind of pre-written software to perform the data transformations needed for binary file I/O.
Accumulate characters
a
in
aS
tri
e
r
n
c
ng
Buffer.