Java Reference
In-Depth Information
write(ByteBuffers[] buffers)) : Writes bytes from each of the buffers in the buffers array 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 methods can throw the same 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 buffers array.
The data that is written from each buffer to the file is determined from that buffer's position and limit, in
the way you have seen. One obvious application of the gathering-write operation is when you are reading
data from several different files into separate buffers, and you want to merge the data into a single file. You
can also use multiple buffers, each with its own view buffer where necessary, as an alternative to multiple
views of a single ByteBuffer . You can see how it works by using yet another variation on the primes-writ-
ing program.
TRY IT OUT: The Gathering Write
In this example, you set up the string length, the string itself, and the binary prime value in separate byte
buffers. You also write the prime string as bytes in the local encoding.
Here's the code:
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.nio.*;
import java.util.*;
import java.io.IOException;
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
Search WWH ::




Custom Search