Java Reference
In-Depth Information
Method
Description
write(ByteBuffers[] buffers)
Writes bytes from each of the buffers in the
array buffers , to the file in sequence, starting
at the channel's current file position.
write(ByteBuffers[] buffers,
int offset,
int length)
Writes data to the file starting at the channel's
current file position from buffers[offset]
to buffers[offset+length-1] inclusive
and in sequence.
Both these methods can throw the same five exceptions as the write method for a single ByteBuffer
object. The second of these methods can also throw an IndexOutOfBoundsException if offset or
offset+length-1 is not a legal index value for the array buffers .
The data that is written from each buffer to the file is determined from that buffer's position and limit in
the way we have seen. One obvious application of the gathering-write operation is when you are
reading data from several different files into a number of buffers, and you want to merge the data into a
single file. We can demonstrate how it works by using a variation on our primes writing program.
Try It Out - The Gathering Write
To simulate conditions where a gathering write could apply, we will set up the string length, the string
itself, and the binary prime value in separate byte buffers. We will also write the prime string as bytes in
the local encoding.
Here's the code:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class GatheringWrite {
public static void main(String[] args) {
int primesRequired = 100; // Default count
if (args.length > 0) {
try {
primesRequired = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException e) {
System.out.println("Prime count value invalid. Using default of "
+ primesRequired);
}
}
long[] primes = new long[primesRequired]; // Array to store primes
primes[0] = 2; // Seed the first prime
primes[1] = 3; // and the second
// Count of primes found - up to now, which is also the array index
int count = 2;
Search WWH ::




Custom Search