Java Reference
In-Depth Information
public void printPart() {
System.out.printf("Part number: %s\n", partNum);
System.out.printf("Part name: %s\n", name);
System.out.printf("Amount in stock: %d\n", amtInStock);
System.out.printf("Price: $%3.2f\n", price);
}
} //end class Part
If EndOfData has the value END , we can read the data from the parts file, assuming it's in the format of the previous
sample data, with this:
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());
}
If there is no more data, the method returns null . Otherwise, it returns a Part object containing the next part's data.
If StringFixedLength denotes the number of characters for storing a part name, we can write a name to the file,
f , with this:
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(' ');
If n denotes the smaller of the actual length of the name and StringFixedLength , we first write n characters
to the file. The second for statement writes blanks to the file to make up the required amount. Note that if
StringFixedLength is shorter than the name, no extra blanks will be written by the last for .
To read a name from the file, we will use the following:
char[] name = new char[StringFixedLength];
for (int h = 0; h < StringFixedLength; h++) name[h] = f.readChar();
String hold = new String(name, 0, StringFixedLength);
This reads exactly StringFixedLength characters from the file into an array. This is then converted into a String
and stored in hold ; hold.trim() will remove the trailing blanks, if any. We will use hold.trim() in creating the Part
object read.
Program P7.6 reads the data from the text file parts.txt and creates the random access file parts.bin .
Program P7.6
import java.io.*;
import java.util.*;
public class CreateRandomAccess {
static final int StringFixedLength = 20;
static final int PartNumSize = 6;
static final int PartRecordSize = 64;
static final String EndOfData = "END";
Search WWH ::




Custom Search