Java Reference
In-Depth Information
7.6.2 Binary File of Records
In the previous section, we created, and read from, a binary file of integers. We now discuss how to work with a binary
file of records, where a record can consist of two or more fields.
Suppose we want to store information on car parts. For now, we assume that each part record has two fields—an
int part number and a double price. Suppose we have a text file parts.txt that contains the parts data in the
following format:
4250 12.95
3000 17.50
6699 49.99
2270 19.25
0
We read this data and create a binary file, parts.bin , with Program P7.4.
Program P7.4
import java.io.*;
import java.util.*;
public class CreateBinaryFile1 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("parts.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("parts.bin"));
int n = in.nextInt();
while (n != 0) {
out.writeInt(n);
out.writeDouble(in.nextDouble());
n = in.nextInt();
}
in.close(); out.close();
} //end main
} //end class CreateBinaryFile1
Each record in parts.bin is exactly 12 bytes (4 for int + 8 for double ). In the example, there are 4 records so the
file will be exactly 48 bytes long. We know that the first record starts at byte 0, the second at byte 12, the third at
byte 24, and the fourth at byte 36. The next record will start at byte 48.
In this scenario, we can easily calculate where record n will start; it will start at byte number ( n - 1) * 12.
To set the stage for what will come later, we will rewrite Program P7.4 using the following Part class:
class Part {
int partNum;
double price;
public Part(int pn, double pr) {
partNum = pn;
price = pr;
}
 
Search WWH ::




Custom Search