Java Reference
In-Depth Information
TOPIC
CONCEPT
Channels
A FileChannel object encapsulates a connection to a file for reading or writing or both.
Obtaining a
Channel for
a File
A FileChannel object for a file is obtained by calling the static newByteChannel() method in the Files
class with a Path object that encapsulates the file path as the first argument. The reference to the object is
returned as type SeekableByteChannel .
Channel In-
terfaces
The FileChannel class implements several channel interfaces including WritableByteChannel that de-
clares the write() method that you use to write to a channel, ReadableByteChannel that declares the
read() method that you use to read from a channel, and SeekableByteChannel that extends the other
two interfaces and declares further methods. The GatheringWriteChannel and GatheringReadChannel
interfaces declare methods that work with arrays of buffers.
Random
Access to a
File
The SeekableByteChannel interface provide the capability for writing to any position in a file.
File Posi-
tion
A file has a position value that indicates the index position in the file where the next byte is written or
read. A FileChannel object keeps track of the current file position and enables you to modify it. The pos-
ition for a file is independent of the position for a buffer.
Buffers
A buffer contains data to be written to a file or data that has been read from a file. Only ByteBuffer ob-
jects can be used directly in file I/O operations using a channel.
Data in a
Buffer
A buffer's position is the index position of the first item of data in the buffer to be written or read. A buf-
fer's limit specifies the index position of the first data item in the buffer that is not to be written or read.
View
Buffers
A view buffer is a buffer that allows the data in a backing byte buffer to be viewed as being of a particular
basic type.
Transferring
Data to and
from a
Buffer
You insert data into a buffer using its put() methods and retrieve data from it using its get() methods.
Relative get() and put() methods increment the buffer's position, whereas absolute get() and put()
methods do not.
Writing a
Buffer to a
Channel
You write the contents of a ByteBuffer object to a file using a write() method belonging to the
FileChannel object for the file.
Data Trans-
fer between
a Buffer
and a Chan-
nel
The amount of data transferred between a buffer and a channel in an I/O operation is determined by the
buffer's position and limit. Data is read or written starting at the file's current position.
Search WWH ::




Custom Search