A file channel is a SeekableByteChannel that is connected to
a file. It has a current position within its file which can
be both queried and modified. The file itself contains a variable-length sequence
of bytes that can be read and written and whose current size can be queried. The size of the file increases
when bytes are written beyond its current size; the size of the file
decreases when it is truncated. The
file may also have some associated metadata such as access
permissions, content type, and last-modification time; this class does not
define methods for metadata access.
In addition to the familiar read, write, and close operations of byte channels, this class defines the following file-specific operations:
Bytes may be read or
written at an absolute
position in a file in a way that does not affect the channel's current
position.
A region of a file may be mapped
directly into memory; for large files this is often much more efficient
than invoking the usual read or write methods.
Updates made to a file may be forced
out to the underlying storage device, ensuring that data are not
lost in the event of a system crash.
Bytes can be transferred from a file to
some other channel, and vice
versa, in a way that can be optimized by many operating systems
into a very fast transfer directly to or from the filesystem cache.
A region of a file may be locked
against access by other programs.
File channels are safe for use by multiple concurrent threads. The
close method may be invoked at any time, as specified
by the Channel interface. Only one operation that involves the
channel's position or can change its file's size may be in progress at any
given time; attempts to initiate a second such operation while the first is
still in progress will block until the first operation completes. Other
operations, in particular those that take an explicit position, may proceed
concurrently; whether they in fact do so is dependent upon the underlying
implementation and is therefore unspecified.
The view of a file provided by an instance of this class is guaranteed to be consistent with other views of the same file provided by other instances in the same program. The view provided by an instance of this class may or may not, however, be consistent with the views seen by other concurrently-running programs due to caching performed by the underlying operating system and delays induced by network-filesystem protocols. This is true regardless of the language in which these other programs are written, and whether they are running on the same machine or on some other machine. The exact nature of any such inconsistencies are system-dependent and are therefore unspecified.
A file channel is created by invoking one of the open
methods defined by this class. A file channel can also be obtained from an
existing FileInputStream, FileOutputStream, or RandomAccessFile object by invoking
that object's getChannel method, which returns a file channel that
is connected to the same underlying file. Where the file channel is obtained
from an existing stream or random access file then the state of the file
channel is intimately connected to that of the object whose getChannel
method returned the channel. Changing the channel's position, whether
explicitly or by reading or writing bytes, will change the file position of
the originating object, and vice versa. Changing the file's length via the
file channel will change the length seen via the originating object, and vice
versa. Changing the file's content by writing bytes will change the content
seen by the originating object, and vice versa. Closing the channel will
close the originating object.
At various points this class specifies that an
instance that is "open for reading," "open for writing," or "open for
reading and writing" is required. A channel obtained via the getChannel method of a java. instance will be open for reading. A channel
obtained via the getChannel
method of a java. instance will be open for
writing. Finally, a channel obtained via the getChannel method of a java. instance will be open for reading if the instance
was created with mode "r" and will be open for reading and writing
if the instance was created with mode "rw".
A file channel that is open for writing may be in
append mode, for example if it was obtained from a file-output stream
that was created by invoking the FileOutputStream(File,boolean) constructor and passing true for
the second parameter. In this mode each invocation of a relative write
operation first advances the position to the end of the file and then writes
the requested data. Whether the advancement of the position and the writing
of the data are done in a single atomic operation is system-dependent and
therefore unspecified. In this mode the behavior of the method to
write at a given position is also
system-dependent.
java.io.FileInputStream#getChannel() , java.io.FileOutputStream#getChannel() , java.io.RandomAccessFile#getChannel()
| Modifier and Type | Class and Description |
|---|---|
| public static class | FileChannel.
A file-mapping mode. |
| Modifier and Type | Field and Description |
|---|---|
| private static final FileAttribute |
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public abstract void | force(boolean
If metaData)true then this method is required to force changes
to both the file's content and metadata to be written to
storage; otherwise, it need only force content changes to be
writtenForces any updates to this channel's file to be written to the storage device that contains it. |
| public abstract FileLock | Returns: A lock object representing the newly-acquired lockThe position at which the locked region is to start; must be
non-negative position, long The size of the locked region; must be non-negative, and the sum
size, boolean position + size must be non-negative.
A value of zero means to lock all bytes from the specified
starting position to the end of the file, regardless of whether
the file is subsequently extended or truncatedtrue to request a shared lock, in which case this
channel must be open for reading (and possibly writing);
false to request an exclusive lock, in which case this
channel must be open for writing (and possibly reading)Acquires a lock on the given region of this channel's file. |
| public final FileLock | Returns: A lock object representing the newly-acquired lockAcquires an exclusive lock on this channel's file. |
| public abstract MappedByteBuffer | Returns: The mapped byte bufferOne of the constants mode,READ_ONLY, READ_WRITE, or PRIVATE defined in the MapMode class, according to
whether the file is to be mapped read-only, read/write, or
privately (copy-on-write), respectively, or an implementation
specific map modeThe position within the file at which the mapped region
is to start; must be non-negative position, long The size of the region to be mapped; must be non-negative and
no greater than size)java.Maps a region of this channel's file directly into memory. |
| public MemorySegment | Returns: A new mapped memory segmentThe file mapping mode, see
mode,FileChannel#map(FileChannel.;
the mapping mode might affect the behavior of the returned
memory mapped segment (see MemorySegment#force())The offset (expressed in bytes) within the file at which the
mapped segment is to start offset, long The size (in bytes) of the mapped memory backing the memory
segment size, Arena The segment arena arena)Maps a region of this channel's file into a new mapped memory segment, with the given offset, size and arena. |
| public static FileChannel | Returns: A new file channelThe path of the file to open or create path, Set<? extends OpenOption> Options specifying how the file is opened options, FileAttribute<?>... An optional list of file attributes to set atomically when
creating the file attrs)Opens or creates a file, returning a file channel to access the file. |
| public static FileChannel | Returns: A new file channelThe path of the file to open or create path, OpenOption... Options specifying how the file is opened options)Opens or creates a file, returning a file channel to access the file. |
| public abstract long | Returns: This channel's file position, a non-negative integer counting the number of bytes from the beginning of the file to the current positionRedeclares java. Returns this channel's file position. |
| public abstract FileChannel | Returns: This file channelThe new position, a non-negative integer counting
the number of bytes from the beginning of the file newPosition)Redeclares java. Sets this channel's file position. |
| public abstract int | read(ByteBuffer dst)
Redeclares java. Reads a sequence of bytes from this channel into the given buffer. |
| public abstract long | read(ByteBuffer[] dsts, int offset, int length)
Redeclares java. Reads a sequence of bytes from this channel into a subsequence of the given buffers. |
| public final long | read(ByteBuffer[] dsts)
Implements java. Reads a sequence of bytes from this channel into the given buffers. |
| public abstract int | Returns: The number of bytes read, possibly zero, or-1 if the
given position is greater than or equal to the file's current
sizeThe buffer into which bytes are to be transferred dst, long The file position at which the transfer is to begin;
must be non-negative position)Reads a sequence of bytes from this channel into the given buffer, starting at the given file position. |
| public abstract long | Returns: The current size of this channel's file, measured in bytesRedeclares java. Returns the current size of this channel's file. |
| public abstract long | Returns: The number of bytes, possibly zero, that were actually transferredThe source channel src, long The file position at which the transfer is to begin;
must be non-negative position, long The maximum number of bytes to be transferred; must be
non-negative count)Transfers bytes into this channel's file from the given readable byte channel. |
| public abstract long | Returns: The number of bytes, possibly zero, that were actually transferredThe position within the file at which the transfer is to begin;
must be non-negative position, long The maximum number of bytes to be transferred; must be
non-negative count, WritableByteChannel The target channel target)Transfers bytes from this channel's file to the given writable byte channel. |
| public abstract FileChannel | Returns: This file channelThe new size, a non-negative byte count size)Redeclares java. Truncates this channel's file to the given size. |
| public abstract FileLock | Returns: A lock object representing the newly-acquired lock, ornull if the lock could not be acquired
because another program holds an overlapping lockThe position at which the locked region is to start; must be
non-negative position, long The size of the locked region; must be non-negative, and the sum
size, boolean position + size must be non-negative.
A value of zero means to lock all bytes from the specified
starting position to the end of the file, regardless of whether
the file is subsequently extended or truncatedtrue to request a shared lock,
false to request an exclusive lockAttempts to acquire a lock on the given region of this channel's file. |
| public final FileLock | Returns: A lock object representing the newly-acquired lock, ornull if the lock could not be acquired
because another program holds an overlapping lockAttempts to acquire an exclusive lock on this channel's file. |
| public abstract int | write(ByteBuffer src)
Redeclares java. Writes a sequence of bytes to this channel from the given buffer. |
| public abstract long | write(ByteBuffer[] srcs, int offset, int length)
Redeclares java. Writes a sequence of bytes to this channel from a subsequence of the given buffers. |
| public final long | write(ByteBuffer[] srcs)
Implements java. Writes a sequence of bytes to this channel from the given buffers. |
| public abstract int | Returns: The number of bytes written, possibly zeroThe buffer from which bytes are to be transferred src, long The file position at which the transfer is to begin;
must be non-negative position)Writes a sequence of bytes to this channel from the given buffer, starting at the given file position. |
| NO_ATTRIBUTES | back to summary |
|---|---|
private static final FileAttribute<?>[] NO_ATTRIBUTES
| |
| FileChannel | back to summary |
|---|---|
| protected FileChannel() Initializes a new instance of this class. | |
| force | back to summary |
|---|---|
| public abstract void force(boolean metaData) throws IOException Forces any updates to this channel's file to be written to the storage device that contains it. If this channel's file resides on a local storage device then when this method returns it is guaranteed that all changes made to the file since this channel was created, or since this method was last invoked, will have been written to that device. This is useful for ensuring that critical information is not lost in the event of a system crash. If the file does not reside on a local device then no such guarantee is made. The Invoking this method may cause an I/O operation to occur even if the channel was only opened for reading. Some operating systems, for example, maintain a last-access time as part of a file's metadata, and this time is updated whenever the file is read. Whether or not this is actually done is system-dependent and is therefore unspecified. This method is only guaranteed to force changes that were made to
this channel's file via the methods defined in this class, or the methods
defined by
| |
| lock | back to summary |
|---|---|
| public abstract FileLock lock(long position, long size, boolean shared) throws IOException Acquires a lock on the given region of this channel's file. An invocation of this method will block until the region can be locked, this channel is closed, or the invoking thread is interrupted, whichever comes first. If this channel is closed by another thread during an invocation of
this method then an If the invoking thread is interrupted while waiting to acquire the
lock then its interrupted status will be set and a The region specified by the Some operating systems do not support shared locks, in which case a
request for a shared lock is automatically converted into a request for
an exclusive lock. Whether the newly-acquired lock is shared or
exclusive may be tested by invoking the resulting lock object's File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
| |
| lock | back to summary |
|---|---|
| public final FileLock lock() throws IOException Acquires an exclusive lock on this channel's file. An invocation of this method of the form fc.lock(0L, Long.MAX_VALUE, false)
| |
| map | back to summary |
|---|---|
| public abstract MappedByteBuffer map(FileChannel. Maps a region of this channel's file directly into memory. The
An implementation may support additional map modes. For a read-only mapping, this channel must have been opened for reading; for a read/write or private mapping, this channel must have been opened for both reading and writing. The A mapping, once established, is not dependent upon the file channel that was used to create it. Closing the channel, in particular, has no effect upon the validity of the mapping. Many of the details of memory-mapped files are inherently dependent upon the underlying operating system and are therefore unspecified. The behavior of this method when the requested region is not completely contained within this channel's file is unspecified. Whether changes made to the content or size of the underlying file, by this program or another, are propagated to the buffer is unspecified. The rate at which changes to the buffer are propagated to the file is unspecified. For most operating systems, mapping a file into memory is more
expensive than reading or writing a few tens of kilobytes of data via
the usual
| |
| map | back to summary |
|---|---|
| public MemorySegment map(FileChannel. Maps a region of this channel's file into a new mapped memory segment, with the given offset, size and arena. The address of the returned memory segment is the starting address of the mapped off-heap region backing the segment. The lifetime of the returned segment is controlled by the provided arena. For instance, if the provided arena is a closeable arena, the returned segment will be unmapped when the provided closeable arena is closed. If the specified mapping mode is
READ_ONLY, the resulting
segment will be read-only (see The content of a mapped memory segment can change at any time, for example if the content of the corresponding region of the mapped file is changed by this (or another) program. Whether such changes occur, and when they occur, is operating-system dependent and therefore unspecified. All or part of a mapped memory segment may become inaccessible at any time, for example if the backing mapped file is truncated. An attempt to access an inaccessible region of a mapped memory segment will not change the segment's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time. It is therefore strongly recommended that appropriate precautions be taken to avoid the manipulation of a mapped file by this (or another) program, except to read or write the file's content. Implementation Note When obtaining a mapped segment from a newly created file channel, the initialization state of the contents of the block of mapped memory associated with the returned mapped memory segment is unspecified and should not be relied upon. Implementation Specification The default implementation of this method throws
| |
| open | back to summary | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException Opens or creates a file, returning a file channel to access the file. The In the addition to
An implementation may also support additional options. The The new channel is created by invoking the
| |||||||||||||||||||
| open | back to summary |
|---|---|
| public static FileChannel open(Path path, OpenOption... options) throws IOException Opens or creates a file, returning a file channel to access the file. An invocation of this method behaves in exactly the same way as the invocation fc.open(file, opts, new FileAttribute<?>[0]); opts is a set of the options specified in the options array.
| |
| position | back to summary |
|---|---|
| public abstract long position() throws IOException Redeclares java. Returns this channel's file position.
| |
| position | back to summary |
|---|---|
| public abstract FileChannel position(long newPosition) throws IOException Redeclares java. Sets this channel's file position. Setting the position to a value that is greater than the file's current size is legal but does not change the size of the file. A later attempt to read bytes at such a position will immediately return an end-of-file indication. A later attempt to write bytes at such a position will cause the file to be grown to accommodate the new bytes; the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified.
| |
| read | back to summary |
|---|---|
| public abstract int read(ByteBuffer dst) throws IOException Redeclares java. Reads a sequence of bytes from this channel into the given buffer. Bytes are read starting at this channel's current file position, and
then the file position is updated with the number of bytes actually
read. Otherwise this method behaves exactly as specified in the
| |
| read | back to summary |
|---|---|
| public abstract long read(ByteBuffer[] dsts, int offset, int length) throws IOException Redeclares java. Reads a sequence of bytes from this channel into a subsequence of the given buffers. Bytes are read starting at this channel's current file position, and
then the file position is updated with the number of bytes actually
read. Otherwise this method behaves exactly as specified in the
| |
| read | back to summary |
|---|---|
| public final long read(ByteBuffer[] dsts) throws IOException Implements java. Reads a sequence of bytes from this channel into the given buffers. Bytes are read starting at this channel's current file position, and
then the file position is updated with the number of bytes actually
read. Otherwise this method behaves exactly as specified in the
| |
| read | back to summary |
|---|---|
| public abstract int read(ByteBuffer dst, long position) throws IOException Reads a sequence of bytes from this channel into the given buffer, starting at the given file position. This method works in the same manner as the
| |
| size | back to summary |
|---|---|
| public abstract long size() throws IOException Redeclares java. Returns the current size of this channel's file.
| |
| transferFrom | back to summary |
|---|---|
| public abstract long transferFrom(ReadableByteChannel src, long position, long count) throws IOException Transfers bytes into this channel's file from the given readable byte channel. An attempt is made to read up to This method does not modify this channel's position. If the given position is greater than or equal to the file's current size then the file will be grown to accommodate the new bytes; the values of any bytes between the previous end-of-file and the newly-written bytes are unspecified. If the source channel has a position then bytes are read starting at that position and then the position is incremented by the number of bytes read. This method is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
| |
| transferTo | back to summary |
|---|---|
| public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException Transfers bytes from this channel's file to the given writable byte channel. An attempt is made to read up to This method does not modify this channel's position. If the given position is greater than or equal to the file's current size then no bytes are transferred. If the target channel has a position then bytes are written starting at that position and then the position is incremented by the number of bytes written. This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
| |
| truncate | back to summary |
|---|---|
| public abstract FileChannel truncate(long size) throws IOException Redeclares java. Truncates this channel's file to the given size. If the given size is less than the file's current size then the file is truncated, discarding any bytes beyond the new end of the file. If the given size is greater than or equal to the file's current size then the file is not modified. In either case, if this channel's file position is greater than the given size then it is set to that size.
| |
| tryLock | back to summary |
|---|---|
| public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException Attempts to acquire a lock on the given region of this channel's file. This method does not block. An invocation always returns
immediately, either having acquired a lock on the requested region or
having failed to do so. If it fails to acquire a lock because an
overlapping lock is held by another program then it returns
The region specified by the Some operating systems do not support shared locks, in which case a
request for a shared lock is automatically converted into a request for
an exclusive lock. Whether the newly-acquired lock is shared or
exclusive may be tested by invoking the resulting lock object's File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
| |
| tryLock | back to summary |
|---|---|
| public final FileLock tryLock() throws IOException Attempts to acquire an exclusive lock on this channel's file. An invocation of this method of the form fc.tryLock(0L, Long.MAX_VALUE, false)
| |
| write | back to summary |
|---|---|
| public abstract int write(ByteBuffer src) throws IOException Redeclares java. Writes a sequence of bytes to this channel from the given buffer. Bytes are written starting at this channel's current file position
unless the channel is in append mode, in which case the position is
first advanced to the end of the file. The file is grown, if necessary,
to accommodate the written bytes, and then the file position is updated
with the number of bytes actually written. Otherwise this method
behaves exactly as specified by the
| |
| write | back to summary |
|---|---|
| public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException Redeclares java. Writes a sequence of bytes to this channel from a subsequence of the given buffers. Bytes are written starting at this channel's current file position
unless the channel is in append mode, in which case the position is
first advanced to the end of the file. The file is grown, if necessary,
to accommodate the written bytes, and then the file position is updated
with the number of bytes actually written. Otherwise this method
behaves exactly as specified in the
| |
| write | back to summary |
|---|---|
| public final long write(ByteBuffer[] srcs) throws IOException Implements java. Writes a sequence of bytes to this channel from the given buffers. Bytes are written starting at this channel's current file position
unless the channel is in append mode, in which case the position is
first advanced to the end of the file. The file is grown, if necessary,
to accommodate the written bytes, and then the file position is updated
with the number of bytes actually written. Otherwise this method
behaves exactly as specified in the
| |
| write | back to summary |
|---|---|
| public abstract int write(ByteBuffer src, long position) throws IOException Writes a sequence of bytes to this channel from the given buffer, starting at the given file position. This method works in the same manner as the If the file is open in append mode, then the effect of invoking this method is unspecified.
| |
java.nio.channels.FileChannel#map
| Modifier and Type | Field and Description |
|---|---|
| private final String | |
| public static final FileChannel. | PRIVATE
Mode for a private (copy-on-write) mapping. |
| public static final FileChannel. | READ_ONLY
Mode for a read-only mapping. |
| public static final FileChannel. | READ_WRITE
Mode for a read/write mapping. |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public String | Returns: A descriptive stringOverrides java. Returns a string describing this file-mapping mode. |
| name | back to summary |
|---|---|
| private final String name | |
| PRIVATE | back to summary |
|---|---|
| public static final FileChannel. Mode for a private (copy-on-write) mapping. | |
| READ_ONLY | back to summary |
|---|---|
| public static final FileChannel. Mode for a read-only mapping. | |
| READ_WRITE | back to summary |
|---|---|
| public static final FileChannel. Mode for a read/write mapping. | |
| MapMode | back to summary |
|---|---|
| private MapMode(String name) Constructs an instance of this class. This constructor may be used by code in java.base to create file mapping modes beyond the file mapping modes defined here.
| |
| toString | back to summary |
|---|---|
| public String toString() Overrides java. Returns a string describing this file-mapping mode.
| |