|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(3) Getting back to the different sizing and positioning values, the four values are known as mark, position, limit, and capacity: - mark -- setable position with
mark method that can be used to reset the position with reset, <= position, >= 0 - position -- current read/write position within buffer, <= limit
- limit -- index of first element that should not be read, <= capacity
- capacity -- size of buffer, >= limit
The position is an important piece of information to keep in mind when reading from and writing to a buffer. For instance, if you want to read what you just wrote you must move the position to where you want to read from, otherwise, you'll read past the limit and get whatever just happens to be there. This is where the flip method comes in handy, changing the limit to the current position and moving the current position to zero. You can also rewind a buffer to keep the current limit and move the position back to zero. For example, removing the flip call from the following snippet will get back a space, assuming nothing was put in the buffer originally. buff.put('a');buff.flip();buff.get();The wrap mechanism shown above is an example of a non-direct buffer. Non-direct buffers can also be created and sized with the allocate method, essentially wrapping the data into an array. At a slightly higher creation cost, you can also create a contiguous memory block, also called a direct buffer, with the allocateDirect method. Direct buffers rely on the system's native I/O operations to optimize Access operations. Mapped FilesThere is one specialized form of direct ByteBuffer known as a MappedByteBuffer. This class represents a buffer of bytes mapped to a file. To map a file to a MappedByteBuffer, you first must get the channel for a file. A channel represents a connection to something, sUCh as a pipe, socket, or file, that can perform I/O operations. In the case of a FileChannel, you can get one from a FileInputStream, FileOutputStream, or RandomAccessFile through the getChannel method. Once you have the channel, you map it to a buffer with map, specifying the mode and portion of the file you want to map. The file channel can be opened read-only (MAP_RO), copy-on-write (MAP_COW), or read-write (MAP_RW).
|