Java Reference
In-Depth Information
try {
System.out.println("File written is " + file.size() + " bytes.");
outputFile.close(); // Close the file and its channel
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
This produces the output:
File written is 800 bytes.
This looks reasonable since we wrote 100 values of type long as binary data and they are 8 bytes each.
How It Works
We create a FileOutputStream object and obtain the channel in the way we have already seen.
Since we did not specify we wanted to append to the file when we created the stream object, the file will
be overwritten each time we run the program.
We create the ByteBuffer object with a capacity of 100 bytes. I chose this value so that it is not an
exact multiple of 8 - the number of bytes occupied by each prime value. This makes the problem more
interesting. You can change the buffer size by change the value set for BUFFERSIZE .
The primes will be transferred to the buffer through a view buffer of type LongBuffer that we obtain
from the original buffer. Since the buffer is too small to hold all the primes, we have to load it and write
the primes to the file in a loop.
The primesWritten variable counts how many primes we have written to the file so we can use this
to control the while loop that writes the primes to the file. The loop continues as long as
primesWritten is less than the number of elements in the primes array. The number of primes that
the LongBuffer object can hold corresponds to longBuf.capacity() .We can transfer this number
of primes to the buffer as long as there is that many left in the array still to be written to the file, so we
do the transfer of a block of primes to the buffer like this:
longBuf.put(primes, primesWritten,
Math.min(longBuf.capacity(),
primes.length - primesWritten));
The first argument to the put() method is the array that is the source of the data and the second argument is
the index position of the first element to be transferred. The third argument will be the capacity of the buffer
as long as there are more than that number of primes still in the array. If there is less than this number on the
last iteration, we will transfer primes.length-primesWritten values to the buffer.
Search WWH ::




Custom Search