public abstract class FileChannel extends Object implements SeekableByteChannel
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 {@codetruncated}
. 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.
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.
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.
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 file channel that is open for writing may be in append mode. 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.
Modifier | Constructor and Description |
---|---|
protected |
FileChannel()
Initializes a new instance of this class.
|
Modifier and Type | Method and Description |
---|---|
void |
close()
Closes this channel.
|
abstract void |
force(boolean metaData)
Forces any updates to this channel's file to be written to the storage
device that contains it.
|
protected abstract void |
implCloseChannel()
Closes this channel.
|
boolean |
isOpen()
Tells whether or not this channel is open.
|
static FileChannel |
open(Path path,
OpenOption... options)
Opens or creates a file, returning a file channel to access the file.
|
static FileChannel |
open(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
Opens or creates a file, returning a file channel to access the file.
|
abstract long |
position()
Returns this channel's file position.
|
abstract FileChannel |
position(long newPosition)
Sets this channel's file position.
|
abstract int |
read(ByteBuffer dst)
Reads a sequence of bytes from this channel into the given buffer.
|
abstract int |
read(ByteBuffer dst,
long position)
Reads a sequence of bytes from this channel into the given buffer,
starting at the given file position.
|
abstract long |
size()
Returns the current size of this channel's file.
|
abstract FileChannel |
truncate(long size)
Truncates this channel's file to the given size.
|
abstract int |
write(ByteBuffer src)
Writes a sequence of bytes to this channel from the given buffer.
|
abstract int |
write(ByteBuffer src,
long position)
Writes a sequence of bytes to this channel from the given buffer,
starting at the given file position.
|
public final void close() throws IOException
Channel
After a channel is closed, any further attempt to invoke I/O
operations upon it will cause a ClosedChannelException
to be
thrown.
If this channel is already closed then invoking this method has no effect.
This method may be invoked at any time. If some other thread has already invoked it, however, then another invocation will block until the first invocation is complete, after which it will return without effect.
close
in interface Closeable
close
in interface AutoCloseable
close
in interface Channel
IOException
- If an I/O error occurspublic abstract void force(boolean metaData) throws IOException
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 metaData parameter can be used to limit the number of I/O operations that this method is required to perform. Passing false for this parameter indicates that only updates to the file's content need be written to storage; passing true indicates that updates to both the file's content and metadata must be written, which generally requires at least one more I/O operation. Whether this parameter actually has any effect is dependent upon the underlying operating system and is therefore unspecified.
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.
metaData
- If 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
writtenClosedChannelException
- If this channel is closedIOException
- If some other I/O error occursprotected abstract void implCloseChannel() throws IOException
This method is invoked by the close
method in order
to perform the actual work of closing the channel. This method is only
invoked if the channel has not yet been closed, and it is never invoked
more than once.
An implementation of this method must arrange for any other thread that is blocked in an I/O operation upon this channel to return immediately, either by throwing an exception or by returning normally.
IOException
- If an I/O error occurs while closing the channelpublic final boolean isOpen()
Channel
public static FileChannel open(Path path, OpenOption... options) throws IOException
An invocation of this method behaves in exactly the same way as the invocation
fc.open
(file, opts, new FileAttribute<?>[0]);
where opts
is a set of the options specified in the options
array.path
- The path of the file to open or createoptions
- Options specifying how the file is openedIllegalArgumentException
- If the set contains an invalid combination of optionsUnsupportedOperationException
- If the path
is associated with a provider that does not
support creating file channels, or an unsupported open option is
specifiedIOException
- If an I/O error occursSecurityException
- If a security manager is installed and it denies an
unspecified permission required by the implementation.
In the case of the default provider, the SecurityManager.checkRead(String)
method is invoked to check
read access if the file is opened for reading. The SecurityManager.checkWrite(String)
method is invoked to check
write access if the file is opened for writingpublic static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException
The options
parameter determines how the file is opened.
The READ
and WRITE
options determine if the file should be opened for reading and/or
writing. If neither option (or the APPEND
option) is contained in the array then the file is opened for reading.
By default reading or writing commences at the beginning of the file.
In the addition to READ
and WRITE
, the following
options may be present:
Option | Description |
---|---|
APPEND |
If this option is present then the file is opened for writing and
each invocation of the channel's write method 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. This option may not be used in conjunction
with the READ or TRUNCATE_EXISTING options. |
TRUNCATE_EXISTING |
If this option is present then the existing file is truncated to a size of 0 bytes. This option is ignored when the file is opened only for reading. |
CREATE_NEW |
If this option is present then a new file is created, failing if the file already exists. When creating a file the check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other file system operations. This option is ignored when the file is opened only for reading. |
CREATE |
If this option is present then an existing file is opened if it
exists, otherwise a new file is created. When creating a file the check
for the existence of the file and the creation of the file if it does
not exist is atomic with respect to other file system operations. This
option is ignored if the CREATE_NEW option is also present or
the file is opened only for reading. |
DELETE_ON_CLOSE |
When this option is present then the implementation makes a
best effort attempt to delete the file when closed by the
the close method. If the close method is not
invoked then a best effort attempt is made to delete the file
when the Java virtual machine terminates. |
SPARSE |
When creating a new file this option is a hint that the new file will be sparse. This option is ignored when not creating a new file. |
SYNC |
Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. (see Synchronized I/O file integrity). |
DSYNC |
Requires that every update to the file's content be written synchronously to the underlying storage device. (see Synchronized I/O file integrity). |
An implementation may also support additional options.
The attrs
parameter is an optional array of file file-attributes
to set atomically when creating the file.
path
- The path of the file to open or createoptions
- Options specifying how the file is openedattrs
- An optional list of file attributes to set atomically when
creating the fileIllegalArgumentException
- If the set contains an invalid combination of optionsUnsupportedOperationException
- If the path
is associated with a provider that does not
support creating file channels, or an unsupported open option is
specified, or the array contains an attribute that cannot be set
atomically when creating the fileIOException
- If an I/O error occursSecurityException
- If a security manager is installed and it denies an
unspecified permission required by the implementation.
In the case of the default provider, the SecurityManager.checkRead(String)
method is invoked to check
read access if the file is opened for reading. The SecurityManager.checkWrite(String)
method is invoked to check
write access if the file is opened for writingpublic abstract long position() throws IOException
position
in interface SeekableByteChannel
ClosedChannelException
- If this channel is closedIOException
- If some other I/O error occurspublic abstract FileChannel position(long newPosition) throws IOException
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.
position
in interface SeekableByteChannel
newPosition
- The new position, a non-negative integer counting
the number of bytes from the beginning of the fileClosedChannelException
- If this channel is closedIllegalArgumentException
- If the new position is negativeIOException
- If some other I/O error occurspublic abstract int read(ByteBuffer dst) throws IOException
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 ReadableByteChannel
interface.
read
in interface ReadableByteChannel
read
in interface SeekableByteChannel
dst
- The buffer into which bytes are to be transferredClosedChannelException
- If this channel is closedAsynchronousCloseException
- If another thread closes this channel
while the read operation is in progressClosedByInterruptException
- If another thread interrupts the current thread
while the read operation is in progress, thereby
closing the channel and setting the current thread's
interrupt statusIOException
- If some other I/O error occurspublic abstract int read(ByteBuffer dst, long position) throws IOException
This method works in the same manner as the read(ByteBuffer)
method, except that bytes are read starting at the
given file position rather than at the channel's current position. This
method does not modify this channel's position. If the given position
is greater than the file's current size then no bytes are read.
dst
- The buffer into which bytes are to be transferredposition
- The file position at which the transfer is to begin;
must be non-negativeIllegalArgumentException
- If the position is negativeNonReadableChannelException
- If this channel was not opened for readingClosedChannelException
- If this channel is closedAsynchronousCloseException
- If another thread closes this channel
while the read operation is in progressClosedByInterruptException
- If another thread interrupts the current thread
while the read operation is in progress, thereby
closing the channel and setting the current thread's
interrupt statusIOException
- If some other I/O error occurspublic abstract long size() throws IOException
size
in interface SeekableByteChannel
ClosedChannelException
- If this channel is closedIOException
- If some other I/O error occurspublic abstract FileChannel truncate(long size) throws IOException
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.
truncate
in interface SeekableByteChannel
size
- The new size, a non-negative byte countNonWritableChannelException
- If this channel was not opened for writingClosedChannelException
- If this channel is closedIllegalArgumentException
- If the new size is negativeIOException
- If some other I/O error occurspublic abstract int write(ByteBuffer src) throws IOException
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 WritableByteChannel
interface.
write
in interface SeekableByteChannel
write
in interface WritableByteChannel
src
- The buffer from which bytes are to be retrievedClosedChannelException
- If this channel is closedAsynchronousCloseException
- If another thread closes this channel
while the write operation is in progressClosedByInterruptException
- If another thread interrupts the current thread
while the write operation is in progress, thereby
closing the channel and setting the current thread's
interrupt statusIOException
- If some other I/O error occurspublic abstract int write(ByteBuffer src, long position) throws IOException
This method works in the same manner as the write(ByteBuffer)
method, except that bytes are written starting at
the given file position rather than at the channel's current position.
This method does not modify this channel's position. If the given
position is greater than 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.
src
- The buffer from which bytes are to be transferredposition
- The file position at which the transfer is to begin;
must be non-negativeIllegalArgumentException
- If the position is negativeNonWritableChannelException
- If this channel was not opened for writingClosedChannelException
- If this channel is closedAsynchronousCloseException
- If another thread closes this channel
while the write operation is in progressClosedByInterruptException
- If another thread interrupts the current thread
while the write operation is in progress, thereby
closing the channel and setting the current thread's
interrupt statusIOException
- If some other I/O error occursCopyright (c) 2014, Oracle and/or its affiliates. All rights reserved. Use of this specification is subject to license terms.