Instead of loading and storing the complete course catalog each time you execute the application, you can dynamically interact with the catalog by implementing it as a random access file. A random access file allows you to quickly seek to specific positions in the file and either read from or write to that position. It would be possible to create a fully featured object database in Java using random access files. The forthcoming example code is a starting point. In Lesson 9, you created a StudentDirectory class. You implemented the class to to store student objects in a HashMap, using the student's ID as a key.
You will implement the student directory using a simple indexed file system. You will store student records in a data file and unique ids (identifiers) for each student in an index file. As you insert a serialized student into the data file, you will record its id, position, and length in the index file. The index file will be small compared to the data file size. It can be quickly loaded into memory and written out when the data file is closed.[2]
The example code is the most involved in this book so far. If you take it a test and method at a time, you shouldn't have much trouble understanding it. Building the tests and code from scratch is a bit more of a challenge. The UML is shown in Figure 11.1. Figure 11.1. The Student DirectoryAnd here is the code. I'll explain the interesting parts of it after the code listing for each class. |