Android
java.nio.channels
public abstract class

java.nio.channels.FileChannel

java.lang.Object
java.nio.channels.spi.AbstractInterruptibleChannel Channel InterruptibleChannel
java.nio.channels.FileChannel ByteChannel GatheringByteChannel ScatteringByteChannel

An abstract channel type for interaction with a platform file.

A FileChannel defines the methods for reading, writing, memory mapping, and manipulating the logical state of a platform file. This type does not have a method for opening files, since this behaviour has been delegated to the FileInputStream, FileOutputStream, and RandomAccessFile types.

FileChannels created from a FileInputStream, or a RandomAccessFile created in mode "r", are read-only. FileChannels created from a FileOutputStream are write-only. FileChannels created from a RandomAccessFile created in mode "rw" are read/write. FileChannels created from a RandomAccessFile that was opened in append-mode will also be in append-mode -- meaning that each write will be proceeded by a seek to the end of file. Some platforms will seek and write atomically, others will not.

FileChannels has a virtual pointer into the file which is referred to as a file position. The position can be manipulated by repositioning it within the file, and its current position can be queried.

FileChannels also have an associated size. The size of the file is the number of bytes that it currently contains. The size can be manipulated by adding more bytes to the end of the file (which increases the size) or truncating the file (which decreases the size). The current size can also be queried.

FileChannels have operations beyond the simple read, write, and close. They can also:

  • request that cached data be forced onto the disk
  • lock ranges of bytes associated with the file
  • transfer data directly to another channel in a manner that has the potential to be optimized by the platform
  • memory-mapping files into NIO buffers to provide efficient manipulation of file data
  • read and write to the file at absolute byte offsets in a fashion that does not modify the current position

FileChannels are thread-safe. Only one operation involving manipulation of the file position may be in-flight at once. Subsequent calls to such operations will block, and one of those blocked will be freed to continue when the first operation has completed. There is no ordered queue or fairness applied to the blocked threads.

It is undefined whether operations that do not manipulate the file position will also block when there are any other operations in-flight.

The logical view of the underlying file is consistent across all FileChannels and IO streams opened on the same file by the same JVM process. Therefore modifications performed via a channel will be visible to the stream, and vice versa; including modifications to the file position, content, size, etc.

Nested Classes
FileChannel.MapMode A type of file mapping modes. 

Summary

Protected Constructors

            FileChannel()
Protected default constructor.

Public Methods

abstract          void  force(boolean metadata)
Request that all updates to the channel are committed to the storage device.
abstract          FileLock  lock(long position, long size, boolean shared)
Obtain a lock on a specified region of the file.
    final      FileLock  lock()
Obtain an exclusive lock on this file.
abstract          MappedByteBuffer  map(FileChannel.MapMode mode, long position, long size)
Maps the file into memory.There can be three modes:Read-only,Read/write and Private.
abstract          long  position()
Returns the current value of the file position pointer.
abstract          FileChannel  position(long offset)
Sets the file position pointer to a new value.
abstract          long  read(ByteBuffer[] buffers, int start, int number)
Reads bytes from the file channel into a subset of the given byte buffers.
abstract          int  read(ByteBuffer buffer)
Reads bytes from the channel into the given byte buffer.
abstract          int  read(ByteBuffer buffer, long position)
Reads bytes from the file channel into the given buffer starting from the given file position.
    final      long  read(ByteBuffer[] buffers)
Reads bytes from the channel into all the given byte buffers.
abstract          long  size()
Returns the size of the file underlying this channel, in bytes.
abstract          long  transferFrom(ReadableByteChannel src, long position, long count)
Transfers bytes into this channel's file from the given readable byte channel.
abstract          long  transferTo(long position, long count, WritableByteChannel target)
Transfers data from the file to the given channel.
abstract          FileChannel  truncate(long size)
Truncates the file underlying this channel to a given size.
    final      FileLock  tryLock()
Attempts to acquire an exclusive lock on this file without blocking.
abstract          FileLock  tryLock(long position, long size, boolean shared)
Attempts to acquire an exclusive lock on this file without blocking.
abstract          long  write(ByteBuffer[] buffers, int offset, int length)
Writes a subset of the given bytes from the buffers to the channel.
abstract          int  write(ByteBuffer buffer, long position)
Writes bytes from the given buffer to the file channel starting at the given file position.
    final      long  write(ByteBuffer[] buffers)
Writes bytes from all the given byte buffers into the file channel.
abstract          int  write(ByteBuffer src)
Writes bytes from the given byte buffer into the file channel.
Methods inherited from class java.nio.channels.spi.AbstractInterruptibleChannel
Methods inherited from class java.lang.Object
Methods inherited from interface java.io.Closeable
Methods inherited from interface java.nio.channels.Channel
Methods inherited from interface java.nio.channels.GatheringByteChannel
Methods inherited from interface java.nio.channels.InterruptibleChannel
Methods inherited from interface java.nio.channels.ReadableByteChannel
Methods inherited from interface java.nio.channels.ScatteringByteChannel
Methods inherited from interface java.nio.channels.WritableByteChannel

Details

Protected Constructors

protected FileChannel()

Protected default constructor.

Public Methods

public abstract void force(boolean metadata)

Request that all updates to the channel are committed to the storage device.

When this method returns all modifications made to the platform file underlying this channel will be committed to a local storage device. If the file is not hosted locally, such as a networked file system, then applications cannot be certain that the modifications have been committed.

There are no assurances given that changes made to the file using methods defined elsewhere will be committed. For example, changes made via a mapped byte buffer may not be committed.

The metadata parameter indicated whether the update should include the file's metadata such as last modification time, last access time, etc. Note that passing true may invoke an underlying write to the operating system (if the platform is maintaining metadata such as last access time), even if the channel is opened read-only.

Parameters

metadata true if the file metadata should be flushed in addition to the file content, and false otherwise.

Throws

ClosedChannelException if the channel is already closed.
IOException some other problem occurred.

public abstract FileLock lock(long position, long size, boolean shared)

Obtain a lock on a specified region of the file.

This is the blocking version of lock acquisition, see also the tryLock() methods.

Attempts to acquire an overlapping lock region will fail. The attempt will fail if the overlapping lock has already been obtained, or if another thread is currently waiting to acquire the overlapping lock.

If the request is not for an overlapping lock, the thread calling this method will block until the lock is obtained (likely by no contention or another process releasing a lock), or this thread being interrupted or the channel closed.

If the lock is obtained successfully then the FileLock object returned represents the lock for subsequent operations on the locked region.

If the thread is interrupted while waiting for the lock, the thread is set to the interrupted state, and throws a FileLockInterruptionException. If the channel is closed while the thread is waiting to obtain the lock then the thread throws a AsynchronousCloseException.

There is no requirement for the position and size to be within the current start and length of the file.

Some platforms do not support shared locks, and if a request is made for a shared lock on such a platform this method will attempt to acquire an exclusive lock instead. It is undefined whether the lock obtained is advisory or mandatory.

Parameters

position the starting position for the lock region
size the length of the lock, in bytes
shared a flag indicating whether an attempt should be made to acquire a shared lock.

Returns

  • the file lock object

Throws

IllegalArgumentException if the parameters are invalid.
ClosedChannelException if the channel is already closed.
OverlappingFileLockException if the requested region overlaps an existing lock or pending lock request.
NonReadableChannelException if the channel is not open in read-mode and shared is true.
NonWritableChannelException if the channel is not open in write mode and shared is false.
AsynchronousCloseException if the channel is closed by another thread while this method is in operation.
FileLockInterruptionException if the thread is interrupted while in the state of waiting on the desired file lock.
IOException if some other IO problem occurs.

public final FileLock lock()

Obtain an exclusive lock on this file.

This is a convenience method for acquiring a maximum length lock on a file. It is equivalent to:

 fileChannel.lock(0L, Long.MAX_VALUE, false)
 

Returns

  • the lock object representing the locked file area.

Throws

ClosedChannelException the file channel is closed.
NonWritableChannelException this channel was not opened for writing.
OverlappingFileLockException Either a lock is already held that overlaps this lock request, or another thread is waiting to acquire a lock that will overlap with this request.
FileLockInterruptionException The calling thread was interrupted while waiting to acquire the lock.
AsynchronousCloseException The channel was closed while the calling thread was waiting to acquire the lock.
IOException some other problem occurred obtaining the requested lock.

public abstract MappedByteBuffer map(FileChannel.MapMode mode, long position, long size)

Maps the file into memory.There can be three modes:Read-only,Read/write and Private. After mapping, the memory and the file channel do not affect each other. Note : mapping a file into memory is usually expensive.

Parameters

mode one of three modes to map
position the starting position of the file
size the size to map

Returns

  • the mapped byte buffer

Throws

NonReadableChannelException If the file is not opened for reading but the given mode is "READ_ONLY"
NonWritableChannelException If the file is not opened for writing but the mode is not "READ_ONLY"
IllegalArgumentException If the given parameters of position and size are not correct
IOException If any I/O error occurs

public abstract long position()

Returns the current value of the file position pointer.

Returns

  • the current position as a positive integer number of bytes from the start of the file.

Throws

ClosedChannelException if the channel is already closed.
IOException if some other IO problem occurs.

public abstract FileChannel position(long offset)

Sets the file position pointer to a new value.

The argument is the number of bytes counted from the start of the file. The position cannot be set to a value that is negative. The new position can be set beyond the current file size. If set beyond the current file size, attempts to read will return end of file, and writes will succeed, but fill-in the bytes between the current end of file and the position with the required number of (unspecified) byte values.

Parameters

offset the new file position, in bytes.

Returns

  • the receiver.

Throws

IllegalArgumentException if the new position is negative.
ClosedChannelException if the channel is already closed.
IOException if some other IO problem occurs.

public abstract long read(ByteBuffer[] buffers, int start, int number)

Reads bytes from the file channel into a subset of the given byte buffers.

Throws

IOException

public abstract int read(ByteBuffer buffer)

Reads bytes from the channel into the given byte buffer.

The bytes are read starting at the current file position, and after some number of bytes are read (up to the remaining number of bytes in the buffer) the file position is increased by the number of bytes actually read.

Throws

IOException

public abstract int read(ByteBuffer buffer, long position)

Reads bytes from the file channel into the given buffer starting from the given file position.

The bytes are read starting at the given file position (up to the remaining number of bytes in the buffer). The number of bytes actually read is returned.

If the position is beyond the current end of file, then no bytes are read.

Note that file position is unmodified by this method.

Parameters

buffer the buffer to receive the bytes
position the (non-negative) position at which to read the bytes.

Returns

  • the number of bytes actually read.

Throws

IllegalArgumentException if position is less than -1.
ClosedChannelException if the channel is already closed.
NonReadableChannelException if the channel was not opened in read-mode.
AsynchronousCloseException if the channel is closed by another thread while this method is in operation.
ClosedByInterruptException if another thread interrupts the calling thread while the operation is in progress. The calling thread will have the interrupt state set, and the channel will be closed.
IOException some other IO error occurred.

public final long read(ByteBuffer[] buffers)

Reads bytes from the channel into all the given byte buffers.

The bytes are read starting at the current file position, and after some number of bytes are read (up to the remaining number of bytes in all the buffers) the file position is increased by the number of bytes actually read.

This method behaves exactly like:

 read(buffers, 0, buffers.length);
 

Throws

IOException

public abstract long size()

Returns the size of the file underlying this channel, in bytes.

Returns

  • the size of the file in bytes.

Throws

ClosedChannelException if the channel is closed.
IOException if a problem occurs getting the size of the file.

public abstract long transferFrom(ReadableByteChannel src, long position, long count)

Transfers bytes into this channel's file from the given readable byte channel. It may be very efficient. By invoking this method, it will read form the source channel and write into the file channel. Note: no guarantee whether all bytes may be transferred. And it does not modify the position of the channel.

Parameters

src the source channel to read
position the non-negative position to begin
count the non-negative bytes to be transferred

Returns

  • the number of bytes that are transferred.

Throws

IllegalArgumentException If the parameters are not correct
NonReadableChannelException If the source channel is not readable
NonWritableChannelException If this channel is not writable
ClosedChannelException If either channel has already been closed
AsynchronousCloseException If either channel is closed by other threads during this operation
ClosedByInterruptException If the thread is interrupted during this operation
IOException If any I/O error occurs

public abstract long transferTo(long position, long count, WritableByteChannel target)

Transfers data from the file to the given channel. It may be very efficient. By invoking this method, it will read form the file and write into the writable channel. Note: no guarantee whether all bytes may be transfered.And it does not modify the position of the channel.

Parameters

position the non-negative position to begin
count the non-negative bytes to be transferred
target the target channel to write into

Returns

  • the number of bytes that were transferred.

Throws

IllegalArgumentException If the parameters are not correct
NonReadableChannelException If this channel is not readable
NonWritableChannelException If the target channel is not writable
ClosedChannelException If either channel has already been closed
AsynchronousCloseException If either channel is closed by other threads during this operation
ClosedByInterruptException If the thread is interrupted during this operation
IOException If any I/O error occurs

public abstract FileChannel truncate(long size)

Truncates the file underlying this channel to a given size.

Any bytes beyond the given size are removed from the file. If there are no bytes beyond the given size then the file contents are unmodified.

If the file position is currently greater than the given size, then it is set to be the given size.

Parameters

size the maximum size of the underlying file

Returns

  • this channel

Throws

IllegalArgumentException the requested size is negative.
ClosedChannelException the channel is closed.
NonWritableChannelException the channel cannot be written.
IOException some other IO problem occurred.

public final FileLock tryLock()

Attempts to acquire an exclusive lock on this file without blocking.

This is a convenience method for attempting to acquire a maximum length lock on the file. It is equivalent to:

 fileChannel.tryLock(0L, Long.MAX_VALUE, false)
 

The method returns null if the acquisition would result in an overlapped lock with another OS process.

Returns

  • the file lock object, or null if the lock would overlap an existing exclusive lock in another OS process.

Throws

ClosedChannelException the file channel is closed.
OverlappingFileLockException Either a lock is already held that overlaps this lock request, or another thread is waiting to acquire a lock that will overlap with this request.
IOException if any I/O error occurs

public abstract FileLock tryLock(long position, long size, boolean shared)

Attempts to acquire an exclusive lock on this file without blocking.

The method returns null if the acquisition would result in an overlapped lock with another OS process.

Parameters

position the starting position
size the size of file to lock
shared true if share

Returns

  • the file lock object, or null if the lock would overlap an existing exclusive lock in another OS process.

Throws

IllegalArgumentException If any parameters are bad
ClosedChannelException the file channel is closed.
OverlappingFileLockException Either a lock is already held that overlaps this lock request, or another thread is waiting to acquire a lock that will overlap with this request.
IOException if any I/O error occurs

public abstract long write(ByteBuffer[] buffers, int offset, int length)

Writes a subset of the given bytes from the buffers to the channel.

This method attempts to write all of the remaining() bytes from length byte buffers, in order, starting at buffers[offset]. The number of bytes actually written is returned.

If a write operation is in progress, subsequent threads will block until the write is completed, and will then contend for the ability to write.

Throws

IOException

public abstract int write(ByteBuffer buffer, long position)

Writes bytes from the given buffer to the file channel starting at the given file position.

The bytes are written starting at the given file position (up to the remaining number of bytes in the buffer). The number of bytes actually written is returned.

If the position is beyond the current end of file, then the file is first extended up to the given position by the required number of unspecified byte values.

Note that file position is unmodified by this method.

Parameters

buffer the buffer containing the bytes to be written.
position the (non-negative) position at which to write the bytes.

Returns

  • the number of bytes actually written.

Throws

IllegalArgumentException if position is less than -1.
ClosedChannelException if the channel is already closed.
NonWritableChannelException if the channel was not opened in write-mode.
AsynchronousCloseException if the channel is closed by another thread while this method is in operation.
ClosedByInterruptException if another thread interrupts the calling thread while the operation is in progress. The calling thread will have the interrupt state set, and the channel will be closed.
IOException some other IO error occurred.

public final long write(ByteBuffer[] buffers)

Writes bytes from all the given byte buffers into the file channel.

The bytes are written starting at the current file position, and after some number of bytes are written (up to the remaining number of bytes in all the buffers) the file position is increased by the number of bytes actually written.

This method behaves exactly like:

 write(buffers, 0, buffers.length);
 

Throws

IOException

public abstract int write(ByteBuffer src)

Writes bytes from the given byte buffer into the file channel.

The bytes are written starting at the current file position, and after some number of bytes are written (up to the remaining number of bytes in the buffer) the file position is increased by the number of bytes actually written.

Parameters

src the source buffer to write

Throws

IOException
Copyright 2007 Google Inc. Build 0.9_r1-98467 - 14 Aug 2008 18:56