Java Reference
In-Depth Information
• The append() methodfirstcalls length() and seek() .Doingsoensures
thatthefilepointerispositionedtotheendofthefilebeforecallingtheprivate
write() method to write a record containing this method's arguments.
• The close() method is declared public because it's inherited from
Closeable and interface methods are public—you cannot make an overrid-
ingmethodlessaccessible. Thismethodisalsodeclaredtothrow IOExcep-
tion because RandomAccessFile 's close() methodcanthrow IOEx-
ception .Becausethisisarareoccurrence,I'vecommentedoutathrowstate-
mentthatyoucanusetoexperimentwithsuppressedexceptions—I'llshowyou
how to do so when I present UsePartsDB .
• The numRecs() method returns the number of records in the file. These re-
cords are numbered starting with 0 and ending with numRecs()-1 . Each of
the select() and update() methodsverifiesthatits recno argumentlies
within this range.
• The select() methodcallstheprivate read() methodtoreturntherecord
identified by recno as an instance of the Part static member class. Part 's
constructor initializes a Part object to a record's field values, and its getter
methods return these values.
• The update() method is equally simple. As with select() , it first posi-
tions the file pointer to the start of the record identified by recno . As with
append() ,itcalls write() towriteoutitsarguments,butreplacesarecord
instead of adding one.
Records are written via the private write() method. Because fields must have
exactsizes, write() pads String -basedvaluesthatareshorterthanafieldsizewith
spaces on the right, and truncates these values to the field size when needed.
Recordsarereadviatheprivate read() method. read() removesthepaddingbe-
fore saving a String -based field value in the Part object.
By itself, PartsDB is useless. We need an application that lets us experiment with
this class, and Listing 8-7 fulfills this requirement.
Listing 8-7. Experimenting with the parts flat file database
import java.io.IOException;
class UsePartsDB
{
 
Search WWH ::




Custom Search