Java Reference
In-Depth Information
Memory-Mapped Files
A memory-mapped file is a file that has its contents mapped into an area of virtual memory in your
computer so you can reference or update the data directly without performing any explicit file read or
write operations on the physical file yourself. The memory that a file maps to may be paged in or out by
the operating system, just like any other memory in your computer, so its immediate availability in real
memory is not guaranteed. Because of the potentially immediate availability of the data it contains, a
memory-mapped file is particularly useful when you need to access the file randomly. Your program
code can reference data in the file as though it were resident in memory.
The map() method for a FileChannel object will return a reference to a buffer of type
MappedByteBuffer that will map to a specified part of the channel's file: :
map(int mode,
long position,
long size)
Maps a region of the channel's file to a buffer of type
MappedByteBuffer . The file region that is mapped starts at
position in the file and is of length size bytes. The first
argument, mode , specifies how the buffer's memory may be
accessed and can be any of the following three constant values,
defined in the FileChannel class:
MAP _ RO. This is valid if the channel was opened for reading the
file, in other words, if the channel was obtained from a
FileInputStream object or a RandomAccessFile object. In
this mode the buffer is read-only. If you try to modify the buffer's
contents a ReadOnlyBufferException will be thrown.
MAP _ RW. This is valid if the channel was obtained from a
RandomAccessFile object with "rw" as its access mode. You can
access and change the contents of the buffer and any changes to
the contents will eventually be propagated to the file.
MAP _ COW. The COW part of the name is for C opy O n W rite. This
option for mode is also only valid if the channel was obtained from
a RandomAccessFile object with "rw" as its access mode. You
can access or change the buffer but changes will not be propagated
to the file. Private copies of modified portions of the buffer will be
created and used for subsequent buffer accesses.
Because the MappedByteBuffer class is a subclass of the ByteBuffer class, you have all the
ByteBuffer methods available for a MappedByteBuffer object. This implies that you can create
view buffers for a MappedByteBuffer object, for instance.
The MappedByteBuffer class defines three methods of its own to add to those inherited from the
ByteBuffer class:
Search WWH ::




Custom Search