The primes.txt file that you created in the previous chapter contains data of three different types. You have the string length as a binary value of type double of all things, followed by the string itself describing the prime value, followed by the binary prime value as type long. Reading this file is a little trickier than it looks at first sight.
To start with you'll set up the file input stream and obtain the channel for the file. Since, apart from the name of the file, this is exactly the same as in the previous example, I won't repeat it here. Of course, the big problem is that you don't know ahead of time exactly how long the strings are. You have two strategies to deal with this:
You can read the string length in the first read operation, then read the string and the binary prime value in the next. The only downside to this approach is that it's not a particularly efficient way to read the file, as you will have read operations that each read a very small amount of data.
You can set up a sizable byte buffer of an arbitrary capacity and just fill it with bytes from the file. You can then sort out what you have in the buffer. The problem with this approach is that the buffer's contents may well end part way through one of the data items from the file. You will have to do some work to detect this and figure out what to do next, but this will be much more efficient than the first approach since you will vastly reduce the number of read operations that ...