Java Reference
In-Depth Information
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("parts.txt"));
RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw");
Part part = getPartData(in);
while (part != null) {
writePartToFile(part, fp);
part = getPartData(in);
}
} //end main
public static Part getPartData(Scanner in) {
String pnum = in.next();
if (pnum.equals(EndOfData)) return null;
return new Part(pnum, in.next(), in.nextInt(), in.nextDouble());
} //end getPartData
public static void writePartToFile(Part part, RandomAccessFile f) throws IOException {
System.out.printf("%s %-11s %2d %5.2f %3d\n", part.partNum, part.name,
part.amtInStock, part.price, f.getFilePointer());
for (int h = 0; h < PartNumSize; h++) f.writeChar(part.partNum.charAt(h));
int n = Math.min(part.name.length(), StringFixedLength);
for (int h = 0; h < n; h++) f.writeChar(part.name.charAt(h));
for (int h = n; h < StringFixedLength; h++) f.writeChar(' ');
f.writeInt(part.amtInStock);
f.writeDouble(part.price);
} //end writePartToFile
} //end class CreateRandomAccess
//class Part goes here
When run with parts.txt containing the previous sample data, Program P7.6 prints the following:
PKL070 Park-Lens 8 6.50 0
BLJ375 Ball-Joint 12 11.95 64
FLT015 Oil-Filter 23 7.95 128
DKP080 Disc-Pads 16 9.99 192
GSF555 Gas-Filter 9 4.50 256
The last value on each line is the file pointer; this is the byte position where the record is stored. The part name is
printed left-justified in a field width of 11 using the format specification %-11s ( - denotes left-justification).
We now write Program P7.7 to test whether the file has been stored correctly. It prompts the user to enter a record
number, and it prints the corresponding part record.
Program P7.7
import java.io.*;
import java.util.*;
public class ReadRandomAccess {
static final int StringFixedLength = 20;
static final int PartNumSize = 6;
static final int PartRecordSize = 64;
Search WWH ::




Custom Search