Java Reference
In-Depth Information
} catch(IOException e) {
e.printStackTrace();
}
}
}
ReadPrimes.java
You should get all the prime values, six to a line, followed by "EOF reached."
How It Works
The code to access the primes in the buffer avoids the possibility of buffer underflow altogether. You al-
ways transfer the number of values available in longBuf by using the remaining() method to determine
the count so you can't cause the BufferUnderflowException to be thrown.
A further possibility is that you could use a buffer large enough to hold all the primes in the file. You can
work this out from the value returned by the size() method for the channel — which is the length of the
file in bytes. You could do that like this:
final int PRIMECOUNT = (int)inCh.size()/LONG_BYTES;
Of course, you also must alter the for loop that outputs the primes so it doesn't attempt to put them all
on the same line. There is a hazard with this though if you don't know how large the file is. Unless your
computer is unusually replete with memory, it could be inconvenient if the file contains the first billion
primes.
Reading Mixed Data
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, which is a strange choice for an integer but good exper-
ience, 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 set up the Path object appropriately and obtain the channel for the file. Because, 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 and 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 because you have many 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 partway through one of the data items from the file. You have to
do some work to detect this and figure out what to do next, but this is much more efficient than
the first approach because you vastly reduce the number of read operations that are necessary to
read the entire file.
Search WWH ::




Custom Search