Java Reference
In-Depth Information
Interface
Method and Description
ScatteringByteChannel
int read(ByteBuffer[] inputs)
Reads bytes from the channel into the array of buffers
specified by the argument, and returns the number of
bytes read, or -1 if the end of the stream is reached.
int read(ByteBuffer[] inputs,
int offset,
int length)
Reads bytes from the channel into length buffers from
the array specified by the first argument starting with the
buffer, inputs[offset] .
GatheringByteChannel
int write(ByteBuffer[] outputs)
Writes bytes from the array of buffers specified by the
argument to the channel, and returns the number of
bytes written.
int write(ByteBuffer[] outputs,
int offset,
int length)
Writes bytes to the channel from length buffers from the
array specified by the first argument, starting with the
buffer, outputs[offset] .
All of these methods can throw exceptions of one kind or another and we will go into details on these
when we come to apply them. Note that a channel only works with buffers of type ByteBuffer . There
are other kinds of buffers as we shall see, but you can't use them directly with the read() and
write() methods for a channel. We will see what determines the number of bytes read or written in
an operation when we discuss buffers in detail.
File Channels
A FileChannel object defines a channel for a physical file, and provides an efficient mechanism for
reading, writing, and manipulating the file. You can't create a FileChannel directly. You first have to
create a file stream object for the file, then obtain a reference to the FileChannel object for the file by
calling the getChannel() method for the file stream object. Here's how you would obtain the channel
for a FileOutputStream object:
File aFile = new File("C:/Beg Java Stuff/myFile.text");
// Place to store an output stream reference
FileOutputStream outputFile = null;
try {
// Create the stream opened to write
outputFile = new FileOutputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
Search WWH ::




Custom Search