Java Reference
In-Depth Information
How It Works
After creating the file path you verify that it does really exist. If the file does not exist, you end the pro-
gram. After you are sure the file is there, you set up the buffers you use to read the file. A
ByteBuffer
is convenient here because you can pass the backing byte array to the
read()
method for the stream to
read the data and use a view buffer for values of type long to retrieve the Fibonacci numbers. You create
the
ByteBuffer
with a capacity for 6 values of type
long
because you can output this many on a single
line. The
totalRead
variable accumulates the number of values that you read from the file.
You create a
BufferedInputStream
object that wraps the
InputStream
object that is returned by the
getInputStream()
method for efficient stream input operations. You don't need to specify any open
options for the file because the default option is
READ
.
You read the file in the indefinite
while
loop into the
bytes
array that backs
buf
. The loop is terminated
when the
read()
method for the stream returns −1, indicating that EOF has been reach. You access the
data that was read through the view buffer,
values
:
for(int i = 0 ; i < numberRead/8 ; ++i) // Access as many
as there are
System.out.format("%12d", values.get());
You can't use the value that the
hasRemaining()
method for the view buffer returns to indicate how
many values you have available because the position and limit for the view buffer are not updated when
you read data into the
bytes
array. The read operation does not involve
buf
or
values
in any direct way
and only the
get()
and
put()
methods for a buffer update the position and limit. However,
numberRead
does reflect the number of bytes actually read from the file, so dividing this by 8 gives you the number
of values read for each operation.
Using
get()
for the view buffer does change its position so you need to call
flip()
for
values
to reset
its state ready for the next loop iteration.
At the end of the
try
block, the stream and the file are closed automatically.
If you want to try marking the input stream to re-read it, you could replace the
try
block in the example
with the following code:
boolean markIt = true;
while(true) {
if(markIt)
fileIn.mark(fileIn.available());
numberRead = fileIn.read(bytes, 0, bytes.length);
if(numberRead == -1) // EOF reached
break;
totalRead += numberRead/8; // Increment total
for(int i = 0 ; i < numberRead/8 ; ++i) // Read long
buffer
System.out.format("%12d", values.get());
System.out.println(); // New line
values.flip(); // Reset for next
input
if(markIt)