A container for data of a specific primitive type.
A buffer is a linear, finite sequence of elements of a specific primitive type. Aside from its content, the essential properties of a buffer are its capacity, limit, and position:
A buffer's capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes.
A buffer's limit is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacity.
A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit.
There is one subclass of this class for each non-boolean primitive type.
Transferring data
Each subclass of this class defines two categories of get and put operations:
Relative operations read or write one or more elements starting at the current position and then increment the position by the number of elements transferred. If the requested transfer exceeds the limit then a relative get operation throws a BufferUnderflowException and a relative put operation throws a BufferOverflowException; in either case, no data is transferred.
Absolute operations take an explicit element index and do not affect the position. Absolute get and put operations throw an IndexOutOfBoundsException if the index argument exceeds the limit.
Data may also, of course, be transferred in to or out of a buffer by the I/O operations of an appropriate channel, which are always relative to the current position.
Marking and resetting
A buffer's mark is the index to which its position will be reset when the reset method is invoked. The mark is not always defined, but when it is defined it is never negative and is never greater than the position. If the mark is defined then it is discarded when the position or the limit is adjusted to a value smaller than the mark. If the mark is not defined then invoking the reset method causes an InvalidMarkException to be thrown.
Invariants
The following invariant holds for the mark, position, limit, and capacity values:
0 <=
mark <=
position <=
limit <=
capacity
A newly-created buffer always has a position of zero and a mark that is undefined. The initial limit may be zero, or it may be some other value that depends upon the type of the buffer and the manner in which it is constructed. Each element of a newly-allocated buffer is initialized to zero.
Clearing, flipping, and rewinding
In addition to methods for accessing the position, limit, and capacity values and for marking and resetting, this class also defines the following operations upon buffers:
clear() makes a buffer ready for a new sequence of channel-read or relative put operations: It sets the limit to the capacity and the position to zero.
flip() makes a buffer ready for a new sequence of channel-write or relative get operations: It sets the limit to the current position and then sets the position to zero.
rewind() makes a buffer ready for re-reading the data that it already contains: It leaves the limit unchanged and sets the position to zero.
Read-only buffers
Every buffer is readable, but not every buffer is writable. The mutation methods of each buffer class are specified as optional operations that will throw a ReadOnlyBufferException when invoked upon a read-only buffer. A read-only buffer does not allow its content to be changed, but its mark, position, and limit values are mutable. Whether or not a buffer is read-only may be determined by invoking its isReadOnly method.
Thread safety
Buffers are not safe for use by multiple concurrent threads. If a buffer is to be used by more than one thread then access to the buffer should be controlled by appropriate synchronization.
Invocation chaining
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained; for example, the sequence of statements
b.flip(); b.position(23); b.limit(42);
can be replaced by the single, more compact statement
b.flip().position(23).limit(42);
A container for data of a specific primitive type. A buffer is a linear, finite sequence of elements of a specific primitive type. Aside from its content, the essential properties of a buffer are its capacity, limit, and position: A buffer's capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes. A buffer's limit is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacity. A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit. There is one subclass of this class for each non-boolean primitive type. Transferring data Each subclass of this class defines two categories of get and put operations: Relative operations read or write one or more elements starting at the current position and then increment the position by the number of elements transferred. If the requested transfer exceeds the limit then a relative get operation throws a BufferUnderflowException and a relative put operation throws a BufferOverflowException; in either case, no data is transferred. Absolute operations take an explicit element index and do not affect the position. Absolute get and put operations throw an IndexOutOfBoundsException if the index argument exceeds the limit. Data may also, of course, be transferred in to or out of a buffer by the I/O operations of an appropriate channel, which are always relative to the current position. Marking and resetting A buffer's mark is the index to which its position will be reset when the reset method is invoked. The mark is not always defined, but when it is defined it is never negative and is never greater than the position. If the mark is defined then it is discarded when the position or the limit is adjusted to a value smaller than the mark. If the mark is not defined then invoking the reset method causes an InvalidMarkException to be thrown. Invariants The following invariant holds for the mark, position, limit, and capacity values: 0 <= mark <= position <= limit <= capacity A newly-created buffer always has a position of zero and a mark that is undefined. The initial limit may be zero, or it may be some other value that depends upon the type of the buffer and the manner in which it is constructed. Each element of a newly-allocated buffer is initialized to zero. Clearing, flipping, and rewinding In addition to methods for accessing the position, limit, and capacity values and for marking and resetting, this class also defines the following operations upon buffers: clear() makes a buffer ready for a new sequence of channel-read or relative put operations: It sets the limit to the capacity and the position to zero. flip() makes a buffer ready for a new sequence of channel-write or relative get operations: It sets the limit to the current position and then sets the position to zero. rewind() makes a buffer ready for re-reading the data that it already contains: It leaves the limit unchanged and sets the position to zero. Read-only buffers Every buffer is readable, but not every buffer is writable. The mutation methods of each buffer class are specified as optional operations that will throw a ReadOnlyBufferException when invoked upon a read-only buffer. A read-only buffer does not allow its content to be changed, but its mark, position, and limit values are mutable. Whether or not a buffer is read-only may be determined by invoking its isReadOnly method. Thread safety Buffers are not safe for use by multiple concurrent threads. If a buffer is to be used by more than one thread then access to the buffer should be controlled by appropriate synchronization. Invocation chaining Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained; for example, the sequence of statements b.flip(); b.position(23); b.limit(42); can be replaced by the single, more compact statement b.flip().position(23).limit(42);
Unchecked exception thrown when a relative put operation reaches the target buffer's limit.
Unchecked exception thrown when a relative put operation reaches the target buffer's limit.
Unchecked exception thrown when a relative get operation reaches the source buffer's limit.
Unchecked exception thrown when a relative get operation reaches the source buffer's limit.
A byte buffer.
This class defines six categories of operations upon byte buffers:
Absolute and relative get and put methods that read and write single bytes;
Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;
Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;
Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;
Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and
Methods for compacting, duplicating, and slicing a byte buffer.
Byte buffers can be created either by allocation, which allocates space for the buffer's
content, or by wrapping an existing byte array into a buffer.
Direct vs. non-direct buffers
A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.
A direct byte buffer may be created by invoking the allocateDirect factory method of this class. The buffers returned by this method typically have somewhat higher allocation and deallocation costs than non-direct buffers. The contents of direct buffers may reside outside of the normal garbage-collected heap, and so their impact upon the memory footprint of an application might not be obvious. It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers that are subject to the underlying system's native I/O operations. In general it is best to allocate direct buffers only when they yield a measureable gain in program performance.
A direct byte buffer may also be created by mapping a region of a file directly into memory. An implementation of the Java platform may optionally support the creation of direct byte buffers from native code via JNI. If an instance of one of these kinds of buffers refers to an inaccessible region of memory then an attempt to access that region will not change the buffer's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time.
Whether a byte buffer is direct or non-direct may be determined by invoking its isDirect method. This method is provided so that explicit buffer management can be done in performance-critical code.
Access to binary data
This class defines methods for reading and writing values of all other primitive types, except boolean. Primitive values are translated to (or from) sequences of bytes according to the buffer's current byte order, which may be retrieved and modified via the order methods. Specific byte orders are represented by instances of the ByteOrder class. The initial order of a byte buffer is always BIG_ENDIAN.
For access to heterogeneous binary data, that is, sequences of values of different types, this class defines a family of absolute and relative get and put methods for each type. For 32-bit floating-point values, for example, this class defines:
float getFloat() float getFloat(int index) void putFloat(float f) void putFloat(int index, float f)
Corresponding methods are defined for the types char, short, int, long, and double. The index parameters of the absolute get and put methods are in terms of bytes rather than of the type being read or written.
For access to homogeneous binary data, that is, sequences of values of the same type, this class defines methods that can create views of a given byte buffer. A view buffer is simply another buffer whose content is backed by the byte buffer. Changes to the byte buffer's content will be visible in the view buffer, and vice versa; the two buffers' position, limit, and mark values are independent. The asFloatBuffer method, for example, creates an instance of the FloatBuffer class that is backed by the byte buffer upon which the method is invoked. Corresponding view-creation methods are defined for the types char, short, int, long, and double.
View buffers have three important advantages over the families of type-specific get and put methods described above:
A view buffer is indexed not in terms of bytes but rather in terms of the type-specific size of its values;
A view buffer provides relative bulk get and put methods that can transfer contiguous sequences of values between a buffer and an array or some other buffer of the same type; and
A view buffer is potentially much more efficient because it will be direct if, and only if, its backing byte buffer is direct.
The byte order of a view buffer is fixed to be that of its byte buffer at the time that the view is created.
Invocation chaining
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
The sequence of statements
bb.putInt(0xCAFEBABE); bb.putShort(3); bb.putShort(45);
can, for example, be replaced by the single statement
bb.putInt(0xCAFEBABE).putShort(3).putShort(45);
A byte buffer. This class defines six categories of operations upon byte buffers: Absolute and relative get and put methods that read and write single bytes; Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array; Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer; Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order; Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and Methods for compacting, duplicating, and slicing a byte buffer. Byte buffers can be created either by allocation, which allocates space for the buffer's content, or by wrapping an existing byte array into a buffer. Direct vs. non-direct buffers A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations. A direct byte buffer may be created by invoking the allocateDirect factory method of this class. The buffers returned by this method typically have somewhat higher allocation and deallocation costs than non-direct buffers. The contents of direct buffers may reside outside of the normal garbage-collected heap, and so their impact upon the memory footprint of an application might not be obvious. It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers that are subject to the underlying system's native I/O operations. In general it is best to allocate direct buffers only when they yield a measureable gain in program performance. A direct byte buffer may also be created by mapping a region of a file directly into memory. An implementation of the Java platform may optionally support the creation of direct byte buffers from native code via JNI. If an instance of one of these kinds of buffers refers to an inaccessible region of memory then an attempt to access that region will not change the buffer's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time. Whether a byte buffer is direct or non-direct may be determined by invoking its isDirect method. This method is provided so that explicit buffer management can be done in performance-critical code. Access to binary data This class defines methods for reading and writing values of all other primitive types, except boolean. Primitive values are translated to (or from) sequences of bytes according to the buffer's current byte order, which may be retrieved and modified via the order methods. Specific byte orders are represented by instances of the ByteOrder class. The initial order of a byte buffer is always BIG_ENDIAN. For access to heterogeneous binary data, that is, sequences of values of different types, this class defines a family of absolute and relative get and put methods for each type. For 32-bit floating-point values, for example, this class defines: float getFloat() float getFloat(int index) void putFloat(float f) void putFloat(int index, float f) Corresponding methods are defined for the types char, short, int, long, and double. The index parameters of the absolute get and put methods are in terms of bytes rather than of the type being read or written. For access to homogeneous binary data, that is, sequences of values of the same type, this class defines methods that can create views of a given byte buffer. A view buffer is simply another buffer whose content is backed by the byte buffer. Changes to the byte buffer's content will be visible in the view buffer, and vice versa; the two buffers' position, limit, and mark values are independent. The asFloatBuffer method, for example, creates an instance of the FloatBuffer class that is backed by the byte buffer upon which the method is invoked. Corresponding view-creation methods are defined for the types char, short, int, long, and double. View buffers have three important advantages over the families of type-specific get and put methods described above: A view buffer is indexed not in terms of bytes but rather in terms of the type-specific size of its values; A view buffer provides relative bulk get and put methods that can transfer contiguous sequences of values between a buffer and an array or some other buffer of the same type; and A view buffer is potentially much more efficient because it will be direct if, and only if, its backing byte buffer is direct. The byte order of a view buffer is fixed to be that of its byte buffer at the time that the view is created. Invocation chaining Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained. The sequence of statements bb.putInt(0xCAFEBABE); bb.putShort(3); bb.putShort(45); can, for example, be replaced by the single statement bb.putInt(0xCAFEBABE).putShort(3).putShort(45);
A typesafe enumeration for byte orders.
A typesafe enumeration for byte orders.
Unchecked exception thrown when an attempt is made to initiate an accept operation on a channel and a previous accept operation has not completed.
Unchecked exception thrown when an attempt is made to initiate an accept operation on a channel and a previous accept operation has not completed.
Unchecked exception thrown when an attempt is made to bind the socket a network oriented channel that is already bound.
Unchecked exception thrown when an attempt is made to bind the socket a network oriented channel that is already bound.
Unchecked exception thrown when an attempt is made to connect a SocketChannel that is already connected.
Unchecked exception thrown when an attempt is made to connect a SocketChannel that is already connected.
An asynchronous channel that can read and write bytes.
Some channels may not allow more than one read or write to be outstanding at any given time. If a thread invokes a read method before a previous read operation has completed then a ReadPendingException will be thrown. Similarly, if a write method is invoked before a previous write has completed then WritePendingException is thrown. Whether or not other kinds of I/O operations may proceed concurrently with a read operation depends upon the type of the channel.
Note that ByteBuffers are not safe for use by multiple concurrent threads. When a read or write operation is initiated then care must be taken to ensure that the buffer is not accessed until the operation completes.
An asynchronous channel that can read and write bytes. Some channels may not allow more than one read or write to be outstanding at any given time. If a thread invokes a read method before a previous read operation has completed then a ReadPendingException will be thrown. Similarly, if a write method is invoked before a previous write has completed then WritePendingException is thrown. Whether or not other kinds of I/O operations may proceed concurrently with a read operation depends upon the type of the channel. Note that ByteBuffers are not safe for use by multiple concurrent threads. When a read or write operation is initiated then care must be taken to ensure that the buffer is not accessed until the operation completes.
A channel that supports asynchronous I/O operations. Asynchronous I/O operations will usually take one of two forms:
Future<V> operation(...)
void operation(... A attachment, CompletionHandler<V,? super A> handler)
where operation is the name of the I/O operation (read or write for example), V is the result type of the I/O operation, and A is the type of an object attached to the I/O operation to provide context when consuming the result. The attachment is important for cases where a state-less CompletionHandler is used to consume the result of many I/O operations.
In the first form, the methods defined by the Future interface may be used to check if the operation has completed, wait for its completion, and to retrieve the result. In the second form, a CompletionHandler is invoked to consume the result of the I/O operation when it completes or fails.
A channel that implements this interface is asynchronously closeable: If an I/O operation is outstanding on the channel and the channel's close method is invoked, then the I/O operation fails with the exception AsynchronousCloseException.
Asynchronous channels are safe for use by multiple concurrent threads. Some channel implementations may support concurrent reading and writing, but may not allow more than one read and one write operation to be outstanding at any given time.
Cancellation
The Future interface defines the cancel method to cancel execution. This causes all threads waiting on the result of the I/O operation to throw CancellationException. Whether the underlying I/O operation can be cancelled is highly implementation specific and therefore not specified. Where cancellation leaves the channel, or the entity to which it is connected, in an inconsistent state, then the channel is put into an implementation specific error state that prevents further attempts to initiate I/O operations that are similar to the operation that was cancelled. For example, if a read operation is cancelled but the implementation cannot guarantee that bytes have not been read from the channel then it puts the channel into an error state; further attempts to initiate a read operation cause an unspecified runtime exception to be thrown. Similarly, if a write operation is cancelled but the implementation cannot guarantee that bytes have not been written to the channel then subsequent attempts to initiate a write will fail with an unspecified runtime exception.
Where the cancel method is invoked with the mayInterruptIfRunning parameter set to true then the I/O operation may be interrupted by closing the channel. In that case all threads waiting on the result of the I/O operation throw CancellationException and any other I/O operations outstanding on the channel complete with the exception AsynchronousCloseException.
Where the cancel method is invoked to cancel read or write operations then it is recommended that all buffers used in the I/O operations be discarded or care taken to ensure that the buffers are not accessed while the channel remains open.
A channel that supports asynchronous I/O operations. Asynchronous I/O operations will usually take one of two forms: Future<V> operation(...) void operation(... A attachment, CompletionHandler<V,? super A> handler) where operation is the name of the I/O operation (read or write for example), V is the result type of the I/O operation, and A is the type of an object attached to the I/O operation to provide context when consuming the result. The attachment is important for cases where a state-less CompletionHandler is used to consume the result of many I/O operations. In the first form, the methods defined by the Future interface may be used to check if the operation has completed, wait for its completion, and to retrieve the result. In the second form, a CompletionHandler is invoked to consume the result of the I/O operation when it completes or fails. A channel that implements this interface is asynchronously closeable: If an I/O operation is outstanding on the channel and the channel's close method is invoked, then the I/O operation fails with the exception AsynchronousCloseException. Asynchronous channels are safe for use by multiple concurrent threads. Some channel implementations may support concurrent reading and writing, but may not allow more than one read and one write operation to be outstanding at any given time. Cancellation The Future interface defines the cancel method to cancel execution. This causes all threads waiting on the result of the I/O operation to throw CancellationException. Whether the underlying I/O operation can be cancelled is highly implementation specific and therefore not specified. Where cancellation leaves the channel, or the entity to which it is connected, in an inconsistent state, then the channel is put into an implementation specific error state that prevents further attempts to initiate I/O operations that are similar to the operation that was cancelled. For example, if a read operation is cancelled but the implementation cannot guarantee that bytes have not been read from the channel then it puts the channel into an error state; further attempts to initiate a read operation cause an unspecified runtime exception to be thrown. Similarly, if a write operation is cancelled but the implementation cannot guarantee that bytes have not been written to the channel then subsequent attempts to initiate a write will fail with an unspecified runtime exception. Where the cancel method is invoked with the mayInterruptIfRunning parameter set to true then the I/O operation may be interrupted by closing the channel. In that case all threads waiting on the result of the I/O operation throw CancellationException and any other I/O operations outstanding on the channel complete with the exception AsynchronousCloseException. Where the cancel method is invoked to cancel read or write operations then it is recommended that all buffers used in the I/O operations be discarded or care taken to ensure that the buffers are not accessed while the channel remains open.
A grouping of asynchronous channels for the purpose of resource sharing.
An asynchronous channel group encapsulates the mechanics required to handle the completion of I/O operations initiated by asynchronous channels that are bound to the group. A group has an associated thread pool to which tasks are submitted to handle I/O events and dispatch to completion-handlers that consume the result of asynchronous operations performed on channels in the group. In addition to handling I/O events, the pooled threads may also execute other tasks required to support the execution of asynchronous I/O operations.
An asynchronous channel group is created by invoking the withFixedThreadPool or withCachedThreadPool methods defined here. Channels are bound to a group by specifying the group when constructing the channel. The associated thread pool is owned by the group; termination of the group results in the shutdown of the associated thread pool.
In addition to groups created explicitly, the Java virtual machine maintains a system-wide default group that is constructed automatically. Asynchronous channels that do not specify a group at construction time are bound to the default group. The default group has an associated thread pool that creates new threads as needed. The default group may be configured by means of system properties defined in the table below. Where the ThreadFactory for the default group is not configured then the pooled threads of the default group are daemon threads.
System property
Description
java.nio.channels.DefaultThreadPool.threadFactory
The value of this property is taken to be the fully-qualified name
of a concrete ThreadFactory
class. The class is loaded using the system class loader and instantiated.
The factory's newThread method is invoked to create each thread for the default
group's thread pool. If the process to load and instantiate the value
of the property fails then an unspecified error is thrown during the
construction of the default group.
java.nio.channels.DefaultThreadPool.initialSize
The value of the initialSize parameter for the default
group (see withCachedThreadPool).
The value of the property is taken to be the String
representation of an Integer that is the initial size parameter.
If the value cannot be parsed as an Integer it causes an
unspecified error to be thrown during the construction of the default
group.
Threading
The completion handler for an I/O operation initiated on a channel bound to a group is guaranteed to be invoked by one of the pooled threads in the group. This ensures that the completion handler is run by a thread with the expected identity.
Where an I/O operation completes immediately, and the initiating thread is one of the pooled threads in the group then the completion handler may be invoked directly by the initiating thread. To avoid stack overflow, an implementation may impose a limit as to the number of activations on the thread stack. Some I/O operations may prohibit invoking the completion handler directly by the initiating thread (see accept).
Shutdown and Termination
The shutdown method is used to initiate an orderly shutdown of a group. An orderly shutdown marks the group as shutdown; further attempts to construct a channel that binds to the group will throw ShutdownChannelGroupException. Whether or not a group is shutdown can be tested using the isShutdown method. Once shutdown, the group terminates when all asynchronous channels that are bound to the group are closed, all actively executing completion handlers have run to completion, and resources used by the group are released. No attempt is made to stop or interrupt threads that are executing completion handlers. The isTerminated method is used to test if the group has terminated, and the awaitTermination method can be used to block until the group has terminated.
The shutdownNow method can be used to initiate a forceful shutdown of the group. In addition to the actions performed by an orderly shutdown, the shutdownNow method closes all open channels in the group as if by invoking the close method.
A grouping of asynchronous channels for the purpose of resource sharing. An asynchronous channel group encapsulates the mechanics required to handle the completion of I/O operations initiated by asynchronous channels that are bound to the group. A group has an associated thread pool to which tasks are submitted to handle I/O events and dispatch to completion-handlers that consume the result of asynchronous operations performed on channels in the group. In addition to handling I/O events, the pooled threads may also execute other tasks required to support the execution of asynchronous I/O operations. An asynchronous channel group is created by invoking the withFixedThreadPool or withCachedThreadPool methods defined here. Channels are bound to a group by specifying the group when constructing the channel. The associated thread pool is owned by the group; termination of the group results in the shutdown of the associated thread pool. In addition to groups created explicitly, the Java virtual machine maintains a system-wide default group that is constructed automatically. Asynchronous channels that do not specify a group at construction time are bound to the default group. The default group has an associated thread pool that creates new threads as needed. The default group may be configured by means of system properties defined in the table below. Where the ThreadFactory for the default group is not configured then the pooled threads of the default group are daemon threads. System property Description java.nio.channels.DefaultThreadPool.threadFactory The value of this property is taken to be the fully-qualified name of a concrete ThreadFactory class. The class is loaded using the system class loader and instantiated. The factory's newThread method is invoked to create each thread for the default group's thread pool. If the process to load and instantiate the value of the property fails then an unspecified error is thrown during the construction of the default group. java.nio.channels.DefaultThreadPool.initialSize The value of the initialSize parameter for the default group (see withCachedThreadPool). The value of the property is taken to be the String representation of an Integer that is the initial size parameter. If the value cannot be parsed as an Integer it causes an unspecified error to be thrown during the construction of the default group. Threading The completion handler for an I/O operation initiated on a channel bound to a group is guaranteed to be invoked by one of the pooled threads in the group. This ensures that the completion handler is run by a thread with the expected identity. Where an I/O operation completes immediately, and the initiating thread is one of the pooled threads in the group then the completion handler may be invoked directly by the initiating thread. To avoid stack overflow, an implementation may impose a limit as to the number of activations on the thread stack. Some I/O operations may prohibit invoking the completion handler directly by the initiating thread (see accept). Shutdown and Termination The shutdown method is used to initiate an orderly shutdown of a group. An orderly shutdown marks the group as shutdown; further attempts to construct a channel that binds to the group will throw ShutdownChannelGroupException. Whether or not a group is shutdown can be tested using the isShutdown method. Once shutdown, the group terminates when all asynchronous channels that are bound to the group are closed, all actively executing completion handlers have run to completion, and resources used by the group are released. No attempt is made to stop or interrupt threads that are executing completion handlers. The isTerminated method is used to test if the group has terminated, and the awaitTermination method can be used to block until the group has terminated. The shutdownNow method can be used to initiate a forceful shutdown of the group. In addition to the actions performed by an orderly shutdown, the shutdownNow method closes all open channels in the group as if by invoking the close method.
Checked exception received by a thread when another thread closes the channel or the part of the channel upon which it is blocked in an I/O operation.
Checked exception received by a thread when another thread closes the channel or the part of the channel upon which it is blocked in an I/O operation.
An asynchronous channel for reading, writing, and manipulating a file.
An asynchronous file channel is created when a file is opened by invoking one of the open methods defined by this class. The file 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.
An asynchronous file channel does not have a current position within the file. Instead, the file position is specified to each read and write method that initiates asynchronous operations. A CompletionHandler is specified as a parameter and is invoked to consume the result of the I/O operation. This class also defines read and write methods that initiate asynchronous operations, returning a Future to represent the pending result of the operation. The Future may be used to check if the operation has completed, wait for its completion, and retrieve the result.
In addition to read and write operations, this class defines the following operations:
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.
A region of a file may be locked against access by other programs.
An AsynchronousFileChannel is associated with a thread pool to which tasks are submitted to handle I/O events and dispatch to completion handlers that consume the results of I/O operations on the channel. The completion handler for an I/O operation initiated on a channel is guaranteed to be invoked by one of the threads in the thread pool (This ensures that the completion handler is run by a thread with the expected identity). Where an I/O operation completes immediately, and the initiating thread is itself a thread in the thread pool, then the completion handler may be invoked directly by the initiating thread. When an AsynchronousFileChannel is created without specifying a thread pool then the channel is associated with a system-dependent default thread pool that may be shared with other channels. The default thread pool is configured by the system properties defined by the AsynchronousChannelGroup class.
Channels of this type are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. This causes all outstanding asynchronous operations on the channel to complete with the exception AsynchronousCloseException. Multiple read and write operations may be outstanding at the same time. When multiple read and write operations are outstanding then the ordering of the I/O operations, and the order that the completion handlers are invoked, is not specified; they are not, in particular, guaranteed to execute in the order that the operations were initiated. The ByteBuffers used when reading or writing are not safe for use by multiple concurrent I/O operations. Furthermore, after an I/O operation is initiated then care should be taken to ensure that the buffer is not accessed until after the operation has completed.
As with FileChannel, 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.
An asynchronous channel for reading, writing, and manipulating a file. An asynchronous file channel is created when a file is opened by invoking one of the open methods defined by this class. The file 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. An asynchronous file channel does not have a current position within the file. Instead, the file position is specified to each read and write method that initiates asynchronous operations. A CompletionHandler is specified as a parameter and is invoked to consume the result of the I/O operation. This class also defines read and write methods that initiate asynchronous operations, returning a Future to represent the pending result of the operation. The Future may be used to check if the operation has completed, wait for its completion, and retrieve the result. In addition to read and write operations, this class defines the following operations: 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. A region of a file may be locked against access by other programs. An AsynchronousFileChannel is associated with a thread pool to which tasks are submitted to handle I/O events and dispatch to completion handlers that consume the results of I/O operations on the channel. The completion handler for an I/O operation initiated on a channel is guaranteed to be invoked by one of the threads in the thread pool (This ensures that the completion handler is run by a thread with the expected identity). Where an I/O operation completes immediately, and the initiating thread is itself a thread in the thread pool, then the completion handler may be invoked directly by the initiating thread. When an AsynchronousFileChannel is created without specifying a thread pool then the channel is associated with a system-dependent default thread pool that may be shared with other channels. The default thread pool is configured by the system properties defined by the AsynchronousChannelGroup class. Channels of this type are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. This causes all outstanding asynchronous operations on the channel to complete with the exception AsynchronousCloseException. Multiple read and write operations may be outstanding at the same time. When multiple read and write operations are outstanding then the ordering of the I/O operations, and the order that the completion handlers are invoked, is not specified; they are not, in particular, guaranteed to execute in the order that the operations were initiated. The ByteBuffers used when reading or writing are not safe for use by multiple concurrent I/O operations. Furthermore, after an I/O operation is initiated then care should be taken to ensure that the buffer is not accessed until after the operation has completed. As with FileChannel, 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.
An asynchronous channel for stream-oriented listening sockets.
An asynchronous server-socket channel is created by invoking the open method of this class. A newly-created asynchronous server-socket channel is open but not yet bound. It can be bound to a local address and configured to listen for connections by invoking the bind method. Once bound, the accept method is used to initiate the accepting of connections to the channel's socket. An attempt to invoke the accept method on an unbound channel will cause a NotYetBoundException to be thrown.
Channels of this type are safe for use by multiple concurrent threads though at most one accept operation can be outstanding at any time. If a thread initiates an accept operation before a previous accept operation has completed then an AcceptPendingException will be thrown.
Socket options are configured using the setOption method. Channels of this type support the following options:
Option Name
Description
SO_RCVBUF
The size of the socket receive buffer
SO_REUSEADDR
Re-use address
Additional (implementation specific) options may also be supported.
Usage Example:
final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));
listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() { public void completed(AsynchronousSocketChannel ch, Void att) { // accept the next connection listener.accept(null, this);
// handle this connection
handle(ch);
}
public void failed(Throwable exc, Void att) {
...
}
});
An asynchronous channel for stream-oriented listening sockets. An asynchronous server-socket channel is created by invoking the open method of this class. A newly-created asynchronous server-socket channel is open but not yet bound. It can be bound to a local address and configured to listen for connections by invoking the bind method. Once bound, the accept method is used to initiate the accepting of connections to the channel's socket. An attempt to invoke the accept method on an unbound channel will cause a NotYetBoundException to be thrown. Channels of this type are safe for use by multiple concurrent threads though at most one accept operation can be outstanding at any time. If a thread initiates an accept operation before a previous accept operation has completed then an AcceptPendingException will be thrown. Socket options are configured using the setOption method. Channels of this type support the following options: Option Name Description SO_RCVBUF The size of the socket receive buffer SO_REUSEADDR Re-use address Additional (implementation specific) options may also be supported. Usage Example: final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000)); listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() { public void completed(AsynchronousSocketChannel ch, Void att) { // accept the next connection listener.accept(null, this); // handle this connection handle(ch); } public void failed(Throwable exc, Void att) { ... } });
An asynchronous channel for stream-oriented connecting sockets.
Asynchronous socket channels are created in one of two ways. A newly-created AsynchronousSocketChannel is created by invoking one of the open methods defined by this class. A newly-created channel is open but not yet connected. A connected AsynchronousSocketChannel is created when a connection is made to the socket of an AsynchronousServerSocketChannel. It is not possible to create an asynchronous socket channel for an arbitrary, pre-existing socket.
A newly-created channel is connected by invoking its connect method; once connected, a channel remains connected until it is closed. Whether or not a socket channel is connected may be determined by invoking its getRemoteAddress method. An attempt to invoke an I/O operation upon an unconnected channel will cause a NotYetConnectedException to be thrown.
Channels of this type are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one read operation and one write operation can be outstanding at any time. If a thread initiates a read operation before a previous read operation has completed then a ReadPendingException will be thrown. Similarly, an attempt to initiate a write operation before a previous write has completed will throw a WritePendingException.
Socket options are configured using the setOption method. Asynchronous socket channels support the following options:
Option Name
Description
SO_SNDBUF
The size of the socket send buffer
SO_RCVBUF
The size of the socket receive buffer
SO_KEEPALIVE
Keep connection alive
SO_REUSEADDR
Re-use address
TCP_NODELAY
Disable the Nagle algorithm
Additional (implementation specific) options may also be supported.
Timeouts
The read and write methods defined by this class allow a timeout to be specified when initiating a read or write operation. If the timeout elapses before an operation completes then the operation completes with the exception InterruptedByTimeoutException. A timeout may leave the channel, or the underlying connection, in an inconsistent state. Where the implementation cannot guarantee that bytes have not been read from the channel then it puts the channel into an implementation specific error state. A subsequent attempt to initiate a read operation causes an unspecified runtime exception to be thrown. Similarly if a write operation times out and the implementation cannot guarantee bytes have not been written to the channel then further attempts to write to the channel cause an unspecified runtime exception to be thrown. When a timeout elapses then the state of the ByteBuffer, or the sequence of buffers, for the I/O operation is not defined. Buffers should be discarded or at least care must be taken to ensure that the buffers are not accessed while the channel remains open. All methods that accept timeout parameters treat values less than or equal to zero to mean that the I/O operation does not timeout.
An asynchronous channel for stream-oriented connecting sockets. Asynchronous socket channels are created in one of two ways. A newly-created AsynchronousSocketChannel is created by invoking one of the open methods defined by this class. A newly-created channel is open but not yet connected. A connected AsynchronousSocketChannel is created when a connection is made to the socket of an AsynchronousServerSocketChannel. It is not possible to create an asynchronous socket channel for an arbitrary, pre-existing socket. A newly-created channel is connected by invoking its connect method; once connected, a channel remains connected until it is closed. Whether or not a socket channel is connected may be determined by invoking its getRemoteAddress method. An attempt to invoke an I/O operation upon an unconnected channel will cause a NotYetConnectedException to be thrown. Channels of this type are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one read operation and one write operation can be outstanding at any time. If a thread initiates a read operation before a previous read operation has completed then a ReadPendingException will be thrown. Similarly, an attempt to initiate a write operation before a previous write has completed will throw a WritePendingException. Socket options are configured using the setOption method. Asynchronous socket channels support the following options: Option Name Description SO_SNDBUF The size of the socket send buffer SO_RCVBUF The size of the socket receive buffer SO_KEEPALIVE Keep connection alive SO_REUSEADDR Re-use address TCP_NODELAY Disable the Nagle algorithm Additional (implementation specific) options may also be supported. Timeouts The read and write methods defined by this class allow a timeout to be specified when initiating a read or write operation. If the timeout elapses before an operation completes then the operation completes with the exception InterruptedByTimeoutException. A timeout may leave the channel, or the underlying connection, in an inconsistent state. Where the implementation cannot guarantee that bytes have not been read from the channel then it puts the channel into an implementation specific error state. A subsequent attempt to initiate a read operation causes an unspecified runtime exception to be thrown. Similarly if a write operation times out and the implementation cannot guarantee bytes have not been written to the channel then further attempts to write to the channel cause an unspecified runtime exception to be thrown. When a timeout elapses then the state of the ByteBuffer, or the sequence of buffers, for the I/O operation is not defined. Buffers should be discarded or at least care must be taken to ensure that the buffers are not accessed while the channel remains open. All methods that accept timeout parameters treat values less than or equal to zero to mean that the I/O operation does not timeout.
A channel that can read and write bytes. This interface simply unifies ReadableByteChannel and WritableByteChannel; it does not specify any new operations.
A channel that can read and write bytes. This interface simply unifies ReadableByteChannel and WritableByteChannel; it does not specify any new operations.
No vars found in this namespace.
Unchecked exception thrown when an attempt is made to use a selection key that is no longer valid.
Unchecked exception thrown when an attempt is made to use a selection key that is no longer valid.
A nexus for I/O operations.
A channel represents an open connection to an entity such as a hardware device, a file, a network socket, or a program component that is capable of performing one or more distinct I/O operations, for example reading or writing.
A channel is either open or closed. A channel is open upon creation, and once closed it remains closed. Once a channel is closed, any attempt to invoke an I/O operation upon it will cause a ClosedChannelException to be thrown. Whether or not a channel is open may be tested by invoking its isOpen method.
Channels are, in general, intended to be safe for multithreaded access as described in the specifications of the interfaces and classes that extend and implement this interface.
A nexus for I/O operations. A channel represents an open connection to an entity such as a hardware device, a file, a network socket, or a program component that is capable of performing one or more distinct I/O operations, for example reading or writing. A channel is either open or closed. A channel is open upon creation, and once closed it remains closed. Once a channel is closed, any attempt to invoke an I/O operation upon it will cause a ClosedChannelException to be thrown. Whether or not a channel is open may be tested by invoking its isOpen method. Channels are, in general, intended to be safe for multithreaded access as described in the specifications of the interfaces and classes that extend and implement this interface.
Utility methods for channels and streams.
This class defines static methods that support the interoperation of the stream classes of the java.io package with the channel classes of this package.
Utility methods for channels and streams. This class defines static methods that support the interoperation of the stream classes of the java.io package with the channel classes of this package.
Checked exception received by a thread when another thread interrupts it while it is blocked in an I/O operation upon a channel. Before this exception is thrown the channel will have been closed and the interrupt status of the previously-blocked thread will have been set.
Checked exception received by a thread when another thread interrupts it while it is blocked in an I/O operation upon a channel. Before this exception is thrown the channel will have been closed and the interrupt status of the previously-blocked thread will have been set.
Checked exception thrown when an attempt is made to invoke or complete an I/O operation upon channel that is closed, or at least closed to that operation. That this exception is thrown does not necessarily imply that the channel is completely closed. A socket channel whose write half has been shut down, for example, may still be open for reading.
Checked exception thrown when an attempt is made to invoke or complete an I/O operation upon channel that is closed, or at least closed to that operation. That this exception is thrown does not necessarily imply that the channel is completely closed. A socket channel whose write half has been shut down, for example, may still be open for reading.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a closed selector.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a closed selector.
A handler for consuming the result of an asynchronous I/O operation.
The asynchronous channels defined in this package allow a completion handler to be specified to consume the result of an asynchronous operation. The completed method is invoked when the I/O operation completes successfully. The failed method is invoked if the I/O operations fails. The implementations of these methods should complete in a timely manner so as to avoid keeping the invoking thread from dispatching to other completion handlers.
A handler for consuming the result of an asynchronous I/O operation. The asynchronous channels defined in this package allow a completion handler to be specified to consume the result of an asynchronous operation. The completed method is invoked when the I/O operation completes successfully. The failed method is invoked if the I/O operations fails. The implementations of these methods should complete in a timely manner so as to avoid keeping the invoking thread from dispatching to other completion handlers.
Unchecked exception thrown when an attempt is made to connect a SocketChannel for which a non-blocking connection operation is already in progress.
Unchecked exception thrown when an attempt is made to connect a SocketChannel for which a non-blocking connection operation is already in progress.
No vars found in this namespace.
A selectable channel for datagram-oriented sockets.
A datagram channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing datagram socket. A newly-created datagram channel is open but not connected. A datagram channel need not be connected in order for the send and receive methods to be used. A datagram channel may be connected, by invoking its connect method, in order to avoid the overhead of the security checks are otherwise performed as part of every send and receive operation. A datagram channel must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses.
Once connected, a datagram channel remains connected until it is disconnected or closed. Whether or not a datagram channel is connected may be determined by invoking its isConnected method.
Socket options are configured using the setOption method. A datagram channel to an Internet Protocol socket supports the following options:
Option Name
Description
SO_SNDBUF
The size of the socket send buffer
SO_RCVBUF
The size of the socket receive buffer
SO_REUSEADDR
Re-use address
SO_BROADCAST
Allow transmission of broadcast datagrams
IP_TOS
The Type of Service (ToS) octet in the Internet Protocol (IP) header
IP_MULTICAST_IF
The network interface for Internet Protocol (IP) multicast datagrams
IP_MULTICAST_TTL
The time-to-live for Internet Protocol (IP) multicast
datagrams
IP_MULTICAST_LOOP
Loopback for Internet Protocol (IP) multicast datagrams
Additional (implementation specific) options may also be supported.
Datagram channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time.
A selectable channel for datagram-oriented sockets. A datagram channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing datagram socket. A newly-created datagram channel is open but not connected. A datagram channel need not be connected in order for the send and receive methods to be used. A datagram channel may be connected, by invoking its connect method, in order to avoid the overhead of the security checks are otherwise performed as part of every send and receive operation. A datagram channel must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses. Once connected, a datagram channel remains connected until it is disconnected or closed. Whether or not a datagram channel is connected may be determined by invoking its isConnected method. Socket options are configured using the setOption method. A datagram channel to an Internet Protocol socket supports the following options: Option Name Description SO_SNDBUF The size of the socket send buffer SO_RCVBUF The size of the socket receive buffer SO_REUSEADDR Re-use address SO_BROADCAST Allow transmission of broadcast datagrams IP_TOS The Type of Service (ToS) octet in the Internet Protocol (IP) header IP_MULTICAST_IF The network interface for Internet Protocol (IP) multicast datagrams IP_MULTICAST_TTL The time-to-live for Internet Protocol (IP) multicast datagrams IP_MULTICAST_LOOP Loopback for Internet Protocol (IP) multicast datagrams Additional (implementation specific) options may also be supported. Datagram channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time.
A channel for reading, writing, mapping, and manipulating a file.
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.
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 FileInputStream instance will be open for reading. A channel obtained via the getChannel method of a FileOutputStream instance will be open for writing. Finally, a channel obtained via the getChannel method of a RandomAccessFile 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.
A channel for reading, writing, mapping, and manipulating a file. 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. 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 FileInputStream instance will be open for reading. A channel obtained via the getChannel method of a FileOutputStream instance will be open for writing. Finally, a channel obtained via the getChannel method of a RandomAccessFile 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.
A typesafe enumeration for file-mapping modes.
A typesafe enumeration for file-mapping modes.
A token representing a lock on a region of a file.
A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class.
A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method.
A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs.
Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock.
The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock.
A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock's state are immutable.
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.
File-lock objects are safe for use by multiple concurrent threads.
Platform dependencies
This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.
Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.
On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory, and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail.
On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file.
Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware's page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 230 or 231. In general, great care should be taken when locking files that reside on network filesystems.
A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method. A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs. Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock. A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock's state are immutable. 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. File-lock objects are safe for use by multiple concurrent threads. Platform dependencies This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written. Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks. On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory, and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail. On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file. Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware's page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 230 or 231. In general, great care should be taken when locking files that reside on network filesystems.
Checked exception received by a thread when another thread interrupts it while it is waiting to acquire a file lock. Before this exception is thrown the interrupt status of the previously-blocked thread will have been set.
Checked exception received by a thread when another thread interrupts it while it is waiting to acquire a file lock. Before this exception is thrown the interrupt status of the previously-blocked thread will have been set.
A channel that can write bytes from a sequence of buffers.
A gathering write operation writes, in a single invocation, a sequence of bytes from one or more of a given sequence of buffers. Gathering writes are often useful when implementing network protocols or file formats that, for example, group data into segments consisting of one or more fixed-length headers followed by a variable-length body. Similar scattering read operations are defined in the ScatteringByteChannel interface.
A channel that can write bytes from a sequence of buffers. A gathering write operation writes, in a single invocation, a sequence of bytes from one or more of a given sequence of buffers. Gathering writes are often useful when implementing network protocols or file formats that, for example, group data into segments consisting of one or more fixed-length headers followed by a variable-length body. Similar scattering read operations are defined in the ScatteringByteChannel interface.
Unchecked exception thrown when a blocking-mode-specific operation is invoked upon a channel in the incorrect blocking mode.
Unchecked exception thrown when a blocking-mode-specific operation is invoked upon a channel in the incorrect blocking mode.
Unchecked exception thrown when an attempt is made to open a channel in a group that was not created by the same provider.
Unchecked exception thrown when an attempt is made to open a channel in a group that was not created by the same provider.
Unchecked exception thrown when an attempt is made to register a channel with a selector that was not created by the provider that created the channel.
Unchecked exception thrown when an attempt is made to register a channel with a selector that was not created by the provider that created the channel.
Checked exception received by a thread when a timeout elapses before an asynchronous operation completes.
Checked exception received by a thread when a timeout elapses before an asynchronous operation completes.
A channel that can be asynchronously closed and interrupted.
A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException.
A channel that implements this interface is also interruptible: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the blocked thread's interrupt method. This will cause the channel to be closed, the blocked thread to receive a ClosedByInterruptException, and the blocked thread's interrupt status to be set.
If a thread's interrupt status is already set and it invokes a blocking I/O operation upon a channel then the channel will be closed and the thread will immediately receive a ClosedByInterruptException; its interrupt status will remain set.
A channel supports asynchronous closing and interruption if, and only if, it implements this interface. This can be tested at runtime, if necessary, via the instanceof operator.
A channel that can be asynchronously closed and interrupted. A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException. A channel that implements this interface is also interruptible: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the blocked thread's interrupt method. This will cause the channel to be closed, the blocked thread to receive a ClosedByInterruptException, and the blocked thread's interrupt status to be set. If a thread's interrupt status is already set and it invokes a blocking I/O operation upon a channel then the channel will be closed and the thread will immediately receive a ClosedByInterruptException; its interrupt status will remain set. A channel supports asynchronous closing and interruption if, and only if, it implements this interface. This can be tested at runtime, if necessary, via the instanceof operator.
A token representing the membership of an Internet Protocol (IP) multicast group.
A membership key may represent a membership to receive all datagrams sent to the group, or it may be source-specific, meaning that it represents a membership that receives only datagrams from a specific source address. Whether or not a membership key is source-specific may be determined by invoking its sourceAddress method.
A membership key is valid upon creation and remains valid until the membership is dropped by invoking the drop method, or the channel is closed. The validity of the membership key may be tested by invoking its isValid method.
Where a membership key is not source-specific and the underlying operation system supports source filtering, then the block and unblock methods can be used to block or unblock multicast datagrams from particular source addresses.
A token representing the membership of an Internet Protocol (IP) multicast group. A membership key may represent a membership to receive all datagrams sent to the group, or it may be source-specific, meaning that it represents a membership that receives only datagrams from a specific source address. Whether or not a membership key is source-specific may be determined by invoking its sourceAddress method. A membership key is valid upon creation and remains valid until the membership is dropped by invoking the drop method, or the channel is closed. The validity of the membership key may be tested by invoking its isValid method. Where a membership key is not source-specific and the underlying operation system supports source filtering, then the block and unblock methods can be used to block or unblock multicast datagrams from particular source addresses.
A network channel that supports Internet Protocol (IP) multicasting.
IP multicasting is the transmission of IP datagrams to members of a group that is zero or more hosts identified by a single destination address.
In the case of a channel to an IPv4 socket, the underlying operating system supports RFC 2236: Internet Group Management Protocol, Version 2 (IGMPv2). It may optionally support source filtering as specified by RFC 3376: Internet Group Management Protocol, Version 3 (IGMPv3). For channels to an IPv6 socket, the equivalent standards are RFC 2710: Multicast Listener Discovery (MLD) for IPv6 and RFC 3810: Multicast Listener Discovery Version 2 (MLDv2) for IPv6.
The join(InetAddress,NetworkInterface) method is used to join a group and receive all multicast datagrams sent to the group. A channel may join several multicast groups and may join the same group on several interfaces. Membership is dropped by invoking the drop method on the returned MembershipKey. If the underlying platform supports source filtering then the block and unblock methods can be used to block or unblock multicast datagrams from particular source addresses.
The join(InetAddress,NetworkInterface,InetAddress) method is used to begin receiving datagrams sent to a group whose source address matches a given source address. This method throws UnsupportedOperationException if the underlying platform does not support source filtering. Membership is cumulative and this method may be invoked again with the same group and interface to allow receiving datagrams from other source addresses. The method returns a MembershipKey that represents membership to receive datagrams from the given source address. Invoking the key's drop method drops membership so that datagrams from the source address can no longer be received.
Platform dependencies
The multicast implementation is intended to map directly to the native multicasting facility. Consequently, the following items should be considered when developing an application that receives IP multicast datagrams:
The creation of the channel should specify the ProtocolFamily that corresponds to the address type of the multicast groups that the channel will join. There is no guarantee that a channel to a socket in one protocol family can join and receive multicast datagrams when the address of the multicast group corresponds to another protocol family. For example, it is implementation specific if a channel to an IPv6 socket can join an IPv4 multicast group and receive multicast datagrams sent to the group.
The channel's socket should be bound to the wildcard address. If the socket is bound to a specific address, rather than the wildcard address then it is implementation specific if multicast datagrams are received by the socket.
The SO_REUSEADDR option should be enabled prior to binding the socket. This is required to allow multiple members of the group to bind to the same address.
Usage Example:
// join multicast group on this interface, and also use this
// interface for outgoing multicast datagrams
NetworkInterface ni = NetworkInterface.getByName("hme0");
DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
.bind(new InetSocketAddress(5000))
.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
InetAddress group = InetAddress.getByName("225.4.5.6");
MembershipKey key = dc.join(group, ni);
A network channel that supports Internet Protocol (IP) multicasting. IP multicasting is the transmission of IP datagrams to members of a group that is zero or more hosts identified by a single destination address. In the case of a channel to an IPv4 socket, the underlying operating system supports RFC 2236: Internet Group Management Protocol, Version 2 (IGMPv2). It may optionally support source filtering as specified by RFC 3376: Internet Group Management Protocol, Version 3 (IGMPv3). For channels to an IPv6 socket, the equivalent standards are RFC 2710: Multicast Listener Discovery (MLD) for IPv6 and RFC 3810: Multicast Listener Discovery Version 2 (MLDv2) for IPv6. The join(InetAddress,NetworkInterface) method is used to join a group and receive all multicast datagrams sent to the group. A channel may join several multicast groups and may join the same group on several interfaces. Membership is dropped by invoking the drop method on the returned MembershipKey. If the underlying platform supports source filtering then the block and unblock methods can be used to block or unblock multicast datagrams from particular source addresses. The join(InetAddress,NetworkInterface,InetAddress) method is used to begin receiving datagrams sent to a group whose source address matches a given source address. This method throws UnsupportedOperationException if the underlying platform does not support source filtering. Membership is cumulative and this method may be invoked again with the same group and interface to allow receiving datagrams from other source addresses. The method returns a MembershipKey that represents membership to receive datagrams from the given source address. Invoking the key's drop method drops membership so that datagrams from the source address can no longer be received. Platform dependencies The multicast implementation is intended to map directly to the native multicasting facility. Consequently, the following items should be considered when developing an application that receives IP multicast datagrams: The creation of the channel should specify the ProtocolFamily that corresponds to the address type of the multicast groups that the channel will join. There is no guarantee that a channel to a socket in one protocol family can join and receive multicast datagrams when the address of the multicast group corresponds to another protocol family. For example, it is implementation specific if a channel to an IPv6 socket can join an IPv4 multicast group and receive multicast datagrams sent to the group. The channel's socket should be bound to the wildcard address. If the socket is bound to a specific address, rather than the wildcard address then it is implementation specific if multicast datagrams are received by the socket. The SO_REUSEADDR option should be enabled prior to binding the socket. This is required to allow multiple members of the group to bind to the same address. Usage Example: // join multicast group on this interface, and also use this // interface for outgoing multicast datagrams NetworkInterface ni = NetworkInterface.getByName("hme0"); DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET) .setOption(StandardSocketOptions.SO_REUSEADDR, true) .bind(new InetSocketAddress(5000)) .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni); InetAddress group = InetAddress.getByName("225.4.5.6"); MembershipKey key = dc.join(group, ni);
A channel to a network socket.
A channel that implements this interface is a channel to a network socket. The bind method is used to bind the socket to a local address, the getLocalAddress method returns the address that the socket is bound to, and the setOption and getOption methods are used to set and query socket options. An implementation of this interface should specify the socket options that it supports.
The bind and setOption methods that do not otherwise have a value to return are specified to return the network channel upon which they are invoked. This allows method invocations to be chained. Implementations of this interface should specialize the return type so that method invocations on the implementation class can be chained.
A channel to a network socket. A channel that implements this interface is a channel to a network socket. The bind method is used to bind the socket to a local address, the getLocalAddress method returns the address that the socket is bound to, and the setOption and getOption methods are used to set and query socket options. An implementation of this interface should specify the socket options that it supports. The bind and setOption methods that do not otherwise have a value to return are specified to return the network channel upon which they are invoked. This allows method invocations to be chained. Implementations of this interface should specialize the return type so that method invocations on the implementation class can be chained.
Unchecked exception thrown when the finishConnect method of a SocketChannel is invoked without first successfully invoking its connect method.
Unchecked exception thrown when the finishConnect method of a SocketChannel is invoked without first successfully invoking its connect method.
Unchecked exception thrown when an attempt is made to read from a channel that was not originally opened for reading.
Unchecked exception thrown when an attempt is made to read from a channel that was not originally opened for reading.
Unchecked exception thrown when an attempt is made to write to a channel that was not originally opened for writing.
Unchecked exception thrown when an attempt is made to write to a channel that was not originally opened for writing.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a server socket channel that is not yet bound.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a server socket channel that is not yet bound.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a socket channel that is not yet connected.
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a socket channel that is not yet connected.
Unchecked exception thrown when an attempt is made to acquire a lock on a region of a file that overlaps a region already locked by the same Java virtual machine, or when another thread is already waiting to lock an overlapping region of the same file.
Unchecked exception thrown when an attempt is made to acquire a lock on a region of a file that overlaps a region already locked by the same Java virtual machine, or when another thread is already waiting to lock an overlapping region of the same file.
A pair of channels that implements a unidirectional pipe.
A pipe consists of a pair of channels: A writable sink channel and a readable source channel. Once some bytes are written to the sink channel they can be read from source channel in exactlyAthe order in which they were written.
Whether or not a thread writing bytes to a pipe will block until another thread reads those bytes, or some previously-written bytes, from the pipe is system-dependent and therefore unspecified. Many pipe implementations will buffer up to a certain number of bytes between the sink and source channels, but such buffering should not be assumed.
A pair of channels that implements a unidirectional pipe. A pipe consists of a pair of channels: A writable sink channel and a readable source channel. Once some bytes are written to the sink channel they can be read from source channel in exactlyAthe order in which they were written. Whether or not a thread writing bytes to a pipe will block until another thread reads those bytes, or some previously-written bytes, from the pipe is system-dependent and therefore unspecified. Many pipe implementations will buffer up to a certain number of bytes between the sink and source channels, but such buffering should not be assumed.
A channel representing the writable end of a Pipe.
A channel representing the writable end of a Pipe.
A channel representing the readable end of a Pipe.
A channel representing the readable end of a Pipe.
A channel that can read bytes.
Only one read operation upon a readable channel may be in progress at any given time. If one thread initiates a read operation upon a channel then any other thread that attempts to initiate another read operation will block until the first operation is complete. Whether or not other kinds of I/O operations may proceed concurrently with a read operation depends upon the type of the channel.
A channel that can read bytes. Only one read operation upon a readable channel may be in progress at any given time. If one thread initiates a read operation upon a channel then any other thread that attempts to initiate another read operation will block until the first operation is complete. Whether or not other kinds of I/O operations may proceed concurrently with a read operation depends upon the type of the channel.
Unchecked exception thrown when an attempt is made to read from an asynchronous socket channel and a previous read has not completed.
Unchecked exception thrown when an attempt is made to read from an asynchronous socket channel and a previous read has not completed.
A channel that can read bytes into a sequence of buffers.
A scattering read operation reads, in a single invocation, a sequence of bytes into one or more of a given sequence of buffers. Scattering reads are often useful when implementing network protocols or file formats that, for example, group data into segments consisting of one or more fixed-length headers followed by a variable-length body. Similar gathering write operations are defined in the GatheringByteChannel interface.
A channel that can read bytes into a sequence of buffers. A scattering read operation reads, in a single invocation, a sequence of bytes into one or more of a given sequence of buffers. Scattering reads are often useful when implementing network protocols or file formats that, for example, group data into segments consisting of one or more fixed-length headers followed by a variable-length body. Similar gathering write operations are defined in the GatheringByteChannel interface.
A byte channel that maintains a current position and allows the position to be changed.
A seekable byte channel is connected to an entity, typically a file, that contains a variable-length sequence of bytes that can be read and written. The current position can be queried and modified. The channel also provides access to the current size of the entity to which the channel is connected. The size increases when bytes are written beyond its current size; the size decreases when it is truncated.
The position and truncate methods which do not otherwise have a value to return are specified to return the channel upon which they are invoked. This allows method invocations to be chained. Implementations of this interface should specialize the return type so that method invocations on the implementation class can be chained.
A byte channel that maintains a current position and allows the position to be changed. A seekable byte channel is connected to an entity, typically a file, that contains a variable-length sequence of bytes that can be read and written. The current position can be queried and modified. The channel also provides access to the current size of the entity to which the channel is connected. The size increases when bytes are written beyond its current size; the size decreases when it is truncated. The position and truncate methods which do not otherwise have a value to return are specified to return the channel upon which they are invoked. This allows method invocations to be chained. Implementations of this interface should specialize the return type so that method invocations on the implementation class can be chained.
A channel that can be multiplexed via a Selector.
In order to be used with a selector, an instance of this class must first be registered via the register method. This method returns a new SelectionKey object that represents the channel's registration with the selector.
Once registered with a selector, a channel remains registered until it is deregistered. This involves deallocating whatever resources were allocated to the channel by the selector.
A channel cannot be deregistered directly; instead, the key representing its registration must be cancelled. Cancelling a key requests that the channel be deregistered during the selector's next selection operation. A key may be cancelled explicitly by invoking its cancel method. All of a channel's keys are cancelled implicitly when the channel is closed, whether by invoking its close method or by interrupting a thread blocked in an I/O operation upon the channel.
If the selector itself is closed then the channel will be deregistered, and the key representing its registration will be invalidated, without further delay.
A channel may be registered at most once with any particular selector.
Whether or not a channel is registered with one or more selectors may be determined by invoking the isRegistered method.
Selectable channels are safe for use by multiple concurrent threads.
Blocking mode
A selectable channel is either in blocking mode or in non-blocking mode. In blocking mode, every I/O operation invoked upon the channel will block until it completes. In non-blocking mode an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all. The blocking mode of a selectable channel may be determined by invoking its isBlocking method.
Newly-created selectable channels are always in blocking mode. Non-blocking mode is most useful in conjunction with selector-based multiplexing. A channel must be placed into non-blocking mode before being registered with a selector, and may not be returned to blocking mode until it has been deregistered.
A channel that can be multiplexed via a Selector. In order to be used with a selector, an instance of this class must first be registered via the register method. This method returns a new SelectionKey object that represents the channel's registration with the selector. Once registered with a selector, a channel remains registered until it is deregistered. This involves deallocating whatever resources were allocated to the channel by the selector. A channel cannot be deregistered directly; instead, the key representing its registration must be cancelled. Cancelling a key requests that the channel be deregistered during the selector's next selection operation. A key may be cancelled explicitly by invoking its cancel method. All of a channel's keys are cancelled implicitly when the channel is closed, whether by invoking its close method or by interrupting a thread blocked in an I/O operation upon the channel. If the selector itself is closed then the channel will be deregistered, and the key representing its registration will be invalidated, without further delay. A channel may be registered at most once with any particular selector. Whether or not a channel is registered with one or more selectors may be determined by invoking the isRegistered method. Selectable channels are safe for use by multiple concurrent threads. Blocking mode A selectable channel is either in blocking mode or in non-blocking mode. In blocking mode, every I/O operation invoked upon the channel will block until it completes. In non-blocking mode an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all. The blocking mode of a selectable channel may be determined by invoking its isBlocking method. Newly-created selectable channels are always in blocking mode. Non-blocking mode is most useful in conjunction with selector-based multiplexing. A channel must be placed into non-blocking mode before being registered with a selector, and may not be returned to blocking mode until it has been deregistered.
A token representing the registration of a SelectableChannel with a Selector.
A selection key is created each time a channel is registered with a selector. A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector. Cancelling a key does not immediately remove it from its selector; it is instead added to the selector's cancelled-key set for removal during the next selection operation. The validity of a key may be tested by invoking its isValid method.
A selection key contains two operation sets represented as integer values. Each bit of an operation set denotes a category of selectable operations that are supported by the key's channel.
The interest set determines which operation categories will be tested for readiness the next time one of the selector's selection methods is invoked. The interest set is initialized with the value given when the key is created; it may later be changed via the interestOps(int) method.
The ready set identifies the operation categories for which the key's channel has been detected to be ready by the key's selector. The ready set is initialized to zero when the key is created; it may later be updated by the selector during a selection operation, but it cannot be updated directly.
That a selection key's ready set indicates that its channel is ready for some operation category is a hint, but not a guarantee, that an operation in such a category may be performed by a thread without causing the thread to block. A ready set is most likely to be accurate immediately after the completion of a selection operation. It is likely to be made inaccurate by external events and by I/O operations that are invoked upon the corresponding channel.
This class defines all known operation-set bits, but precisely which bits are supported by a given channel depends upon the type of the channel. Each subclass of SelectableChannel defines an validOps() method which returns a set identifying just those operations that are supported by the channel. An attempt to set or test an operation-set bit that is not supported by a key's channel will result in an appropriate run-time exception.
It is often necessary to associate some application-specific data with a selection key, for example an object that represents the state of a higher-level protocol and handles readiness notifications in order to implement that protocol. Selection keys therefore support the attachment of a single arbitrary object to a key. An object can be attached via the attach method and then later retrieved via the attachment method.
Selection keys are safe for use by multiple concurrent threads. The operations of reading and writing the interest set will, in general, be synchronized with certain operations of the selector. Exactly how this synchronization is performed is implementation-dependent: In a naive implementation, reading or writing the interest set may block indefinitely if a selection operation is already in progress; in a high-performance implementation, reading or writing the interest set may block briefly, if at all. In any case, a selection operation will always use the interest-set value that was current at the moment that the operation began.
A token representing the registration of a SelectableChannel with a Selector. A selection key is created each time a channel is registered with a selector. A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector. Cancelling a key does not immediately remove it from its selector; it is instead added to the selector's cancelled-key set for removal during the next selection operation. The validity of a key may be tested by invoking its isValid method. A selection key contains two operation sets represented as integer values. Each bit of an operation set denotes a category of selectable operations that are supported by the key's channel. The interest set determines which operation categories will be tested for readiness the next time one of the selector's selection methods is invoked. The interest set is initialized with the value given when the key is created; it may later be changed via the interestOps(int) method. The ready set identifies the operation categories for which the key's channel has been detected to be ready by the key's selector. The ready set is initialized to zero when the key is created; it may later be updated by the selector during a selection operation, but it cannot be updated directly. That a selection key's ready set indicates that its channel is ready for some operation category is a hint, but not a guarantee, that an operation in such a category may be performed by a thread without causing the thread to block. A ready set is most likely to be accurate immediately after the completion of a selection operation. It is likely to be made inaccurate by external events and by I/O operations that are invoked upon the corresponding channel. This class defines all known operation-set bits, but precisely which bits are supported by a given channel depends upon the type of the channel. Each subclass of SelectableChannel defines an validOps() method which returns a set identifying just those operations that are supported by the channel. An attempt to set or test an operation-set bit that is not supported by a key's channel will result in an appropriate run-time exception. It is often necessary to associate some application-specific data with a selection key, for example an object that represents the state of a higher-level protocol and handles readiness notifications in order to implement that protocol. Selection keys therefore support the attachment of a single arbitrary object to a key. An object can be attached via the attach method and then later retrieved via the attachment method. Selection keys are safe for use by multiple concurrent threads. The operations of reading and writing the interest set will, in general, be synchronized with certain operations of the selector. Exactly how this synchronization is performed is implementation-dependent: In a naive implementation, reading or writing the interest set may block indefinitely if a selection operation is already in progress; in a high-performance implementation, reading or writing the interest set may block briefly, if at all. In any case, a selection operation will always use the interest-set value that was current at the moment that the operation began.
A multiplexor of SelectableChannel objects.
A selector may be created by invoking the open method of this class, which will use the system's default selector provider to create a new selector. A selector may also be created by invoking the openSelector method of a custom selector provider. A selector remains open until it is closed via its close method.
A selectable channel's registration with a selector is represented by a SelectionKey object. A selector maintains three sets of selection keys:
The key set contains the keys representing the current channel registrations of this selector. This set is returned by the keys method.
The selected-key set is the set of keys such that each key's channel was detected to be ready for at least one of the operations identified in the key's interest set during a prior selection operation. This set is returned by the selectedKeys method. The selected-key set is always a subset of the key set.
The cancelled-key set is the set of keys that have been cancelled but whose channels have not yet been deregistered. This set is not directly accessible. The cancelled-key set is always a subset of the key set.
All three sets are empty in a newly-created selector.
A key is added to a selector's key set as a side effect of registering a channel via the channel's register method. Cancelled keys are removed from the key set during selection operations. The key set itself is not directly modifiable.
A key is added to its selector's cancelled-key set when it is cancelled, whether by closing its channel or by invoking its cancel method. Cancelling a key will cause its channel to be deregistered during the next selection operation, at which time the key will removed from all of the selector's key sets.
Keys are added to the selected-key set by selection operations. A key may be removed directly from the selected-key set by invoking the set's remove method or by invoking the remove method of an iterator obtained from the set. Keys are never removed from the selected-key set in any other way; they are not, in particular, removed as a side effect of selection operations. Keys may not be added directly to the selected-key set.
Selection
During each selection operation, keys may be added to and removed from a selector's selected-key set and may be removed from its key and cancelled-key sets. Selection is performed by the select(), select(long), and selectNow() methods, and involves three steps:
Each key in the cancelled-key set is removed from each key set of which it is a member, and its channel is deregistered. This step leaves the cancelled-key set empty.
The underlying operating system is queried for an update as to the readiness of each remaining channel to perform any of the operations identified by its key's interest set as of the moment that the selection operation began. For a channel that is ready for at least one such operation, one of the following two actions is performed:
If the channel's key is not already in the selected-key set then
it is added to that set and its ready-operation set is modified to
identify exactly those operations for which the channel is now reported
to be ready. Any readiness information previously recorded in the ready
set is discarded.
Otherwise the channel's key is already in the selected-key set,
so its ready-operation set is modified to identify any new operations
for which the channel is reported to be ready. Any readiness
information previously recorded in the ready set is preserved; in other
words, the ready set returned by the underlying system is
bitwise-disjoined into the key's current ready set.
If all of the keys in the key set at the start of this step have empty interest sets then neither the selected-key set nor any of the keys' ready-operation sets will be updated.
If any keys were added to the cancelled-key set while step (2) was in progress then they are processed as in step (1).
Whether or not a selection operation blocks to wait for one or more channels to become ready, and if so for how long, is the only essential difference between the three selection methods.
Concurrency
Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
The selection operations synchronize on the selector itself, on the key set, and on the selected-key set, in that order. They also synchronize on the cancelled-key set during steps (1) and (3) above.
Changes made to the interest sets of a selector's keys while a selection operation is in progress have no effect upon that operation; they will be seen by the next selection operation.
Keys may be cancelled and channels may be closed at any time. Hence the presence of a key in one or more of a selector's key sets does not imply that the key is valid or that its channel is open. Application code should be careful to synchronize and check these conditions as necessary if there is any possibility that another thread will cancel a key or close a channel.
A thread blocked in one of the select() or select(long) methods may be interrupted by some other thread in one of three ways:
By invoking the selector's wakeup method,
By invoking the selector's close method, or
By invoking the blocked thread's interrupt method, in which case its interrupt status will be set and the selector's wakeup method will be invoked.
The close method synchronizes on the selector and all three key sets in the same order as in a selection operation.
A selector's key and selected-key sets are not, in general, safe for use by multiple concurrent threads. If such a thread might modify one of these sets directly then access should be controlled by synchronizing on the set itself. The iterators returned by these sets' iterator methods are fail-fast: If the set is modified after the iterator is created, in any way except by invoking the iterator's own remove method, then a ConcurrentModificationException will be thrown.
A multiplexor of SelectableChannel objects. A selector may be created by invoking the open method of this class, which will use the system's default selector provider to create a new selector. A selector may also be created by invoking the openSelector method of a custom selector provider. A selector remains open until it is closed via its close method. A selectable channel's registration with a selector is represented by a SelectionKey object. A selector maintains three sets of selection keys: The key set contains the keys representing the current channel registrations of this selector. This set is returned by the keys method. The selected-key set is the set of keys such that each key's channel was detected to be ready for at least one of the operations identified in the key's interest set during a prior selection operation. This set is returned by the selectedKeys method. The selected-key set is always a subset of the key set. The cancelled-key set is the set of keys that have been cancelled but whose channels have not yet been deregistered. This set is not directly accessible. The cancelled-key set is always a subset of the key set. All three sets are empty in a newly-created selector. A key is added to a selector's key set as a side effect of registering a channel via the channel's register method. Cancelled keys are removed from the key set during selection operations. The key set itself is not directly modifiable. A key is added to its selector's cancelled-key set when it is cancelled, whether by closing its channel or by invoking its cancel method. Cancelling a key will cause its channel to be deregistered during the next selection operation, at which time the key will removed from all of the selector's key sets. Keys are added to the selected-key set by selection operations. A key may be removed directly from the selected-key set by invoking the set's remove method or by invoking the remove method of an iterator obtained from the set. Keys are never removed from the selected-key set in any other way; they are not, in particular, removed as a side effect of selection operations. Keys may not be added directly to the selected-key set. Selection During each selection operation, keys may be added to and removed from a selector's selected-key set and may be removed from its key and cancelled-key sets. Selection is performed by the select(), select(long), and selectNow() methods, and involves three steps: Each key in the cancelled-key set is removed from each key set of which it is a member, and its channel is deregistered. This step leaves the cancelled-key set empty. The underlying operating system is queried for an update as to the readiness of each remaining channel to perform any of the operations identified by its key's interest set as of the moment that the selection operation began. For a channel that is ready for at least one such operation, one of the following two actions is performed: If the channel's key is not already in the selected-key set then it is added to that set and its ready-operation set is modified to identify exactly those operations for which the channel is now reported to be ready. Any readiness information previously recorded in the ready set is discarded. Otherwise the channel's key is already in the selected-key set, so its ready-operation set is modified to identify any new operations for which the channel is reported to be ready. Any readiness information previously recorded in the ready set is preserved; in other words, the ready set returned by the underlying system is bitwise-disjoined into the key's current ready set. If all of the keys in the key set at the start of this step have empty interest sets then neither the selected-key set nor any of the keys' ready-operation sets will be updated. If any keys were added to the cancelled-key set while step (2) was in progress then they are processed as in step (1). Whether or not a selection operation blocks to wait for one or more channels to become ready, and if so for how long, is the only essential difference between the three selection methods. Concurrency Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not. The selection operations synchronize on the selector itself, on the key set, and on the selected-key set, in that order. They also synchronize on the cancelled-key set during steps (1) and (3) above. Changes made to the interest sets of a selector's keys while a selection operation is in progress have no effect upon that operation; they will be seen by the next selection operation. Keys may be cancelled and channels may be closed at any time. Hence the presence of a key in one or more of a selector's key sets does not imply that the key is valid or that its channel is open. Application code should be careful to synchronize and check these conditions as necessary if there is any possibility that another thread will cancel a key or close a channel. A thread blocked in one of the select() or select(long) methods may be interrupted by some other thread in one of three ways: By invoking the selector's wakeup method, By invoking the selector's close method, or By invoking the blocked thread's interrupt method, in which case its interrupt status will be set and the selector's wakeup method will be invoked. The close method synchronizes on the selector and all three key sets in the same order as in a selection operation. A selector's key and selected-key sets are not, in general, safe for use by multiple concurrent threads. If such a thread might modify one of these sets directly then access should be controlled by synchronizing on the set itself. The iterators returned by these sets' iterator methods are fail-fast: If the set is modified after the iterator is created, in any way except by invoking the iterator's own remove method, then a ConcurrentModificationException will be thrown.
A selectable channel for stream-oriented listening sockets.
A server-socket channel is created by invoking the open method of this class. It is not possible to create a channel for an arbitrary, pre-existing ServerSocket. A newly-created server-socket channel is open but not yet bound. An attempt to invoke the accept method of an unbound server-socket channel will cause a NotYetBoundException to be thrown. A server-socket channel can be bound by invoking one of the bind methods defined by this class.
Socket options are configured using the setOption method. Server-socket channels support the following options:
Option Name
Description
SO_RCVBUF
The size of the socket receive buffer
SO_REUSEADDR
Re-use address
Additional (implementation specific) options may also be supported.
Server-socket channels are safe for use by multiple concurrent threads.
A selectable channel for stream-oriented listening sockets. A server-socket channel is created by invoking the open method of this class. It is not possible to create a channel for an arbitrary, pre-existing ServerSocket. A newly-created server-socket channel is open but not yet bound. An attempt to invoke the accept method of an unbound server-socket channel will cause a NotYetBoundException to be thrown. A server-socket channel can be bound by invoking one of the bind methods defined by this class. Socket options are configured using the setOption method. Server-socket channels support the following options: Option Name Description SO_RCVBUF The size of the socket receive buffer SO_REUSEADDR Re-use address Additional (implementation specific) options may also be supported. Server-socket channels are safe for use by multiple concurrent threads.
Unchecked exception thrown when an attempt is made to construct a channel in a group that is shutdown or the completion handler for an I/O operation cannot be invoked because the channel group has terminated.
Unchecked exception thrown when an attempt is made to construct a channel in a group that is shutdown or the completion handler for an I/O operation cannot be invoked because the channel group has terminated.
A selectable channel for stream-oriented connecting sockets.
A socket channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing socket. A newly-created socket channel is open but not yet connected. An attempt to invoke an I/O operation upon an unconnected channel will cause a NotYetConnectedException to be thrown. A socket channel can be connected by invoking its connect method; once connected, a socket channel remains connected until it is closed. Whether or not a socket channel is connected may be determined by invoking its isConnected method.
Socket channels support non-blocking connection: A socket channel may be created and the process of establishing the link to the remote socket may be initiated via the connect method for later completion by the finishConnect method. Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method.
Socket channels support asynchronous shutdown, which is similar to the asynchronous close operation specified in the Channel class. If the input side of a socket is shut down by one thread while another thread is blocked in a read operation on the socket's channel, then the read operation in the blocked thread will complete without reading any bytes and will return -1. If the output side of a socket is shut down by one thread while another thread is blocked in a write operation on the socket's channel, then the blocked thread will receive an AsynchronousCloseException.
Socket options are configured using the setOption method. Socket channels support the following options:
Option Name
Description
SO_SNDBUF
The size of the socket send buffer
SO_RCVBUF
The size of the socket receive buffer
SO_KEEPALIVE
Keep connection alive
SO_REUSEADDR
Re-use address
SO_LINGER
Linger on close if data is present (when configured in blocking mode
only)
TCP_NODELAY
Disable the Nagle algorithm
Additional (implementation specific) options may also be supported.
Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time. The connect and finishConnect methods are mutually synchronized against each other, and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete.
A selectable channel for stream-oriented connecting sockets. A socket channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing socket. A newly-created socket channel is open but not yet connected. An attempt to invoke an I/O operation upon an unconnected channel will cause a NotYetConnectedException to be thrown. A socket channel can be connected by invoking its connect method; once connected, a socket channel remains connected until it is closed. Whether or not a socket channel is connected may be determined by invoking its isConnected method. Socket channels support non-blocking connection: A socket channel may be created and the process of establishing the link to the remote socket may be initiated via the connect method for later completion by the finishConnect method. Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method. Socket channels support asynchronous shutdown, which is similar to the asynchronous close operation specified in the Channel class. If the input side of a socket is shut down by one thread while another thread is blocked in a read operation on the socket's channel, then the read operation in the blocked thread will complete without reading any bytes and will return -1. If the output side of a socket is shut down by one thread while another thread is blocked in a write operation on the socket's channel, then the blocked thread will receive an AsynchronousCloseException. Socket options are configured using the setOption method. Socket channels support the following options: Option Name Description SO_SNDBUF The size of the socket send buffer SO_RCVBUF The size of the socket receive buffer SO_KEEPALIVE Keep connection alive SO_REUSEADDR Re-use address SO_LINGER Linger on close if data is present (when configured in blocking mode only) TCP_NODELAY Disable the Nagle algorithm Additional (implementation specific) options may also be supported. Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time. The connect and finishConnect methods are mutually synchronized against each other, and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete.
Base implementation class for interruptible channels.
This class encapsulates the low-level machinery required to implement the asynchronous closing and interruption of channels. A concrete channel class must invoke the begin and end methods before and after, respectively, invoking an I/O operation that might block indefinitely. In order to ensure that the end method is always invoked, these methods should be used within a try ... finally block:
boolean completed = false; try { begin(); completed = ...; // Perform blocking I/O operation return ...; // Return result } finally { end(completed); }
The completed argument to the end method tells whether or not the I/O operation actually completed, that is, whether it had any effect that would be visible to the invoker. In the case of an operation that reads bytes, for example, this argument should be true if, and only if, some bytes were actually transferred into the invoker's target buffer.
A concrete channel class must also implement the implCloseChannel method in such a way that if it is invoked while another thread is blocked in a native I/O operation upon the channel then that operation will immediately return, either by throwing an exception or by returning normally. If a thread is interrupted or the channel upon which it is blocked is asynchronously closed then the channel's end method will throw the appropriate exception.
This class performs the synchronization required to implement the Channel specification. Implementations of the implCloseChannel method need not synchronize against other threads that might be attempting to close the channel.
Base implementation class for interruptible channels. This class encapsulates the low-level machinery required to implement the asynchronous closing and interruption of channels. A concrete channel class must invoke the begin and end methods before and after, respectively, invoking an I/O operation that might block indefinitely. In order to ensure that the end method is always invoked, these methods should be used within a try ... finally block: boolean completed = false; try { begin(); completed = ...; // Perform blocking I/O operation return ...; // Return result } finally { end(completed); } The completed argument to the end method tells whether or not the I/O operation actually completed, that is, whether it had any effect that would be visible to the invoker. In the case of an operation that reads bytes, for example, this argument should be true if, and only if, some bytes were actually transferred into the invoker's target buffer. A concrete channel class must also implement the implCloseChannel method in such a way that if it is invoked while another thread is blocked in a native I/O operation upon the channel then that operation will immediately return, either by throwing an exception or by returning normally. If a thread is interrupted or the channel upon which it is blocked is asynchronously closed then the channel's end method will throw the appropriate exception. This class performs the synchronization required to implement the Channel specification. Implementations of the implCloseChannel method need not synchronize against other threads that might be attempting to close the channel.
Base implementation class for selectable channels.
This class defines methods that handle the mechanics of channel registration, deregistration, and closing. It maintains the current blocking mode of this channel as well as its current set of selection keys. It performs all of the synchronization required to implement the SelectableChannel specification. Implementations of the abstract protected methods defined in this class need not synchronize against other threads that might be engaged in the same operations.
Base implementation class for selectable channels. This class defines methods that handle the mechanics of channel registration, deregistration, and closing. It maintains the current blocking mode of this channel as well as its current set of selection keys. It performs all of the synchronization required to implement the SelectableChannel specification. Implementations of the abstract protected methods defined in this class need not synchronize against other threads that might be engaged in the same operations.
Base implementation class for selection keys.
This class tracks the validity of the key and implements cancellation.
Base implementation class for selection keys. This class tracks the validity of the key and implements cancellation.
Base implementation class for selectors.
This class encapsulates the low-level machinery required to implement the interruption of selection operations. A concrete selector class must invoke the begin and end methods before and after, respectively, invoking an I/O operation that might block indefinitely. In order to ensure that the end method is always invoked, these methods should be used within a try ... finally block:
try { begin(); // Perform blocking I/O operation here ... } finally { end(); }
This class also defines methods for maintaining a selector's cancelled-key set and for removing a key from its channel's key set, and declares the abstract register method that is invoked by a selectable channel's register method in order to perform the actual work of registering a channel.
Base implementation class for selectors. This class encapsulates the low-level machinery required to implement the interruption of selection operations. A concrete selector class must invoke the begin and end methods before and after, respectively, invoking an I/O operation that might block indefinitely. In order to ensure that the end method is always invoked, these methods should be used within a try ... finally block: try { begin(); // Perform blocking I/O operation here ... } finally { end(); } This class also defines methods for maintaining a selector's cancelled-key set and for removing a key from its channel's key set, and declares the abstract register method that is invoked by a selectable channel's register method in order to perform the actual work of registering a channel.
Service-provider class for asynchronous channels.
An asynchronous channel provider is a concrete subclass of this class that has a zero-argument constructor and implements the abstract methods specified below. A given invocation of the Java virtual machine maintains a single system-wide default provider instance, which is returned by the provider method. The first invocation of that method will locate the default provider as specified below.
All of the methods in this class are safe for use by multiple concurrent threads.
Service-provider class for asynchronous channels. An asynchronous channel provider is a concrete subclass of this class that has a zero-argument constructor and implements the abstract methods specified below. A given invocation of the Java virtual machine maintains a single system-wide default provider instance, which is returned by the provider method. The first invocation of that method will locate the default provider as specified below. All of the methods in this class are safe for use by multiple concurrent threads.
No vars found in this namespace.
Service-provider class for selectors and selectable channels.
A selector provider is a concrete subclass of this class that has a zero-argument constructor and implements the abstract methods specified below. A given invocation of the Java virtual machine maintains a single system-wide default provider instance, which is returned by the provider method. The first invocation of that method will locate the default provider as specified below.
The system-wide default provider is used by the static open methods of the DatagramChannel, Pipe, Selector, ServerSocketChannel, and SocketChannel classes. It is also used by the System.inheritedChannel() method. A program may make use of a provider other than the default provider by instantiating that provider and then directly invoking the open methods defined in this class.
All of the methods in this class are safe for use by multiple concurrent threads.
Service-provider class for selectors and selectable channels. A selector provider is a concrete subclass of this class that has a zero-argument constructor and implements the abstract methods specified below. A given invocation of the Java virtual machine maintains a single system-wide default provider instance, which is returned by the provider method. The first invocation of that method will locate the default provider as specified below. The system-wide default provider is used by the static open methods of the DatagramChannel, Pipe, Selector, ServerSocketChannel, and SocketChannel classes. It is also used by the System.inheritedChannel() method. A program may make use of a provider other than the default provider by instantiating that provider and then directly invoking the open methods defined in this class. All of the methods in this class are safe for use by multiple concurrent threads.
Unchecked exception thrown when an attempt is made to invoke a network operation upon an unresolved socket address.
Unchecked exception thrown when an attempt is made to invoke a network operation upon an unresolved socket address.
Unchecked exception thrown when an attempt is made to bind or connect to a socket address of a type that is not supported.
Unchecked exception thrown when an attempt is made to bind or connect to a socket address of a type that is not supported.
A channel that can write bytes.
Only one write operation upon a writable channel may be in progress at any given time. If one thread initiates a write operation upon a channel then any other thread that attempts to initiate another write operation will block until the first operation is complete. Whether or not other kinds of I/O operations may proceed concurrently with a write operation depends upon the type of the channel.
A channel that can write bytes. Only one write operation upon a writable channel may be in progress at any given time. If one thread initiates a write operation upon a channel then any other thread that attempts to initiate another write operation will block until the first operation is complete. Whether or not other kinds of I/O operations may proceed concurrently with a write operation depends upon the type of the channel.
Unchecked exception thrown when an attempt is made to write to an asynchronous socket channel and a previous write has not completed.
Unchecked exception thrown when an attempt is made to write to an asynchronous socket channel and a previous write has not completed.
A char buffer.
This class defines four categories of operations upon char buffers:
Absolute and relative get and put methods that read and write single chars;
Relative bulk get methods that transfer contiguous sequences of chars from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of chars from a char array, a string, or some other char buffer into this buffer; and
Methods for compacting, duplicating, and slicing a char buffer.
Char buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing char array or string into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, a char buffer is either direct or non-direct. A char buffer created via the wrap methods of this class will be non-direct. A char buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a char buffer is direct may be determined by invoking the isDirect method.
This class implements the CharSequence interface so that character buffers may be used wherever character sequences are accepted, for example in the regular-expression package java.util.regex.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
The sequence of statements
cb.put("text/"); cb.put(subtype); cb.put("; charset="); cb.put(enc);
can, for example, be replaced by the single statement
cb.put("text/").put(subtype).put("; charset=").put(enc);
A char buffer. This class defines four categories of operations upon char buffers: Absolute and relative get and put methods that read and write single chars; Relative bulk get methods that transfer contiguous sequences of chars from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of chars from a char array, a string, or some other char buffer into this buffer; and Methods for compacting, duplicating, and slicing a char buffer. Char buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing char array or string into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a char buffer is either direct or non-direct. A char buffer created via the wrap methods of this class will be non-direct. A char buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a char buffer is direct may be determined by invoking the isDirect method. This class implements the CharSequence interface so that character buffers may be used wherever character sequences are accepted, for example in the regular-expression package java.util.regex. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained. The sequence of statements cb.put("text/"); cb.put(subtype); cb.put("; charset="); cb.put(enc); can, for example, be replaced by the single statement cb.put("text/").put(subtype).put("; charset=").put(enc);
Checked exception thrown when a character encoding or decoding error occurs.
Checked exception thrown when a character encoding or decoding error occurs.
A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes. This class defines methods for creating decoders and encoders and for retrieving the various names associated with a charset. Instances of this class are immutable.
This class also defines static methods for testing whether a particular charset is supported, for locating charset instances by name, and for constructing a map that contains every charset for which support is available in the current Java virtual machine. Support for new charsets can be added via the service-provider interface defined in the CharsetProvider class.
All of the methods defined in this class are safe for use by multiple concurrent threads.
Charset names
Charsets are named by strings composed of the following characters:
The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'),
The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'),
The digits '0' through '9' ('\u0030' through '\u0039'),
The dash character '-' ('\u002d', HYPHEN-MINUS),
The plus character '+' ('\u002b', PLUS SIGN),
The period character '.' ('\u002e', FULL STOP),
The colon character ':' ('\u003a', COLON), and
The underscore character '_' ('\u005f', LOW LINE).
A charset name must begin with either a letter or a digit. The empty string is not a legal charset name. Charset names are not case-sensitive; that is, case is always ignored when comparing charset names. Charset names generally follow the conventions documented in RFC 2278: IANA Charset Registration Procedures.
Every charset has a canonical name and may also have one or more aliases. The canonical name is returned by the name method of this class. Canonical names are, by convention, usually in upper case. The aliases of a charset are returned by the aliases method.
Some charsets have an historical name that is defined for compatibility with previous versions of the Java platform. A charset's historical name is either its canonical name or one of its aliases. The historical name is returned by the getEncoding() methods of the InputStreamReader and OutputStreamWriter classes.
If a charset listed in the IANA Charset Registry is supported by an implementation of the Java platform then its canonical name must be the name listed in the registry. Many charsets are given more than one name in the registry, in which case the registry identifies one of the names as MIME-preferred. If a charset has more than one registry name then its canonical name must be the MIME-preferred name and the other names in the registry must be valid aliases. If a supported charset is not listed in the IANA registry then its canonical name must begin with one of the strings "X-" or "x-".
The IANA charset registry does change over time, and so the canonical name and the aliases of a particular charset may also change over time. To ensure compatibility it is recommended that no alias ever be removed from a charset, and that if the canonical name of a charset is changed then its previous canonical name be made into an alias.
Standard charsets
Every implementation of the Java platform is required to support the following standard charsets. Consult the release documentation for your implementation to see if any other charsets are supported. The behavior of such optional charsets may differ between implementations.
CharsetDescription US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 UTF-8 Eight-bit UCS Transformation Format UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
The UTF-8 charset is specified by RFC 2279; the transformation format upon which it is based is specified in Amendment 2 of ISO 10646-1 and is also described in the Unicode Standard.
The UTF-16 charsets are specified by RFC 2781; the transformation formats upon which they are based are specified in Amendment 1 of ISO 10646-1 and are also described in the Unicode Standard.
The UTF-16 charsets use sixteen-bit quantities and are therefore sensitive to byte order. In these encodings the byte order of a stream may be indicated by an initial byte-order mark represented by the Unicode character '\uFEFF'. Byte-order marks are handled as follows:
When decoding, the UTF-16BE and UTF-16LE charsets interpret the initial byte-order marks as a ZERO-WIDTH NON-BREAKING SPACE; when encoding, they do not write byte-order marks.
When decoding, the UTF-16 charset interprets the byte-order mark at the beginning of the input stream to indicate the byte-order of the stream but defaults to big-endian if there is no byte-order mark; when encoding, it uses big-endian byte order and writes a big-endian byte-order mark.
In any case, byte order marks occurring after the first element of an input sequence are not omitted since the same code is used to represent ZERO-WIDTH NON-BREAKING SPACE.
Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.
The StandardCharsets class defines constants for each of the standard charsets.
Terminology
The name of this class is taken from the terms used in RFC 2278. In that document a charset is defined as the combination of one or more coded character sets and a character-encoding scheme. (This definition is confusing; some other software systems define charset as a synonym for coded character set.)
A coded character set is a mapping between a set of abstract characters and a set of integers. US-ASCII, ISO 8859-1, JIS X 0201, and Unicode are examples of coded character sets.
Some standards have defined a character set to be simply a set of abstract characters without an associated assigned numbering. An alphabet is an example of such a character set. However, the subtle distinction between character set and coded character set is rarely used in practice; the former has become a short form for the latter, including in the Java API specification.
A character-encoding scheme is a mapping between one or more coded character sets and a set of octet (eight-bit byte) sequences. UTF-8, UTF-16, ISO 2022, and EUC are examples of character-encoding schemes. Encoding schemes are often associated with a particular coded character set; UTF-8, for example, is used only to encode Unicode. Some schemes, however, are associated with multiple coded character sets; EUC, for example, can be used to encode characters in a variety of Asian coded character sets.
When a coded character set is used exclusively with a single character-encoding scheme then the corresponding charset is usually named for the coded character set; otherwise a charset is usually named for the encoding scheme and, possibly, the locale of the coded character sets that it supports. Hence US-ASCII is both the name of a coded character set and of the charset that encodes it, while EUC-JP is the name of the charset that encodes the JIS X 0201, JIS X 0208, and JIS X 0212 coded character sets for the Japanese language.
The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units (that is, sequences of chars) and sequences of bytes.
A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes. This class defines methods for creating decoders and encoders and for retrieving the various names associated with a charset. Instances of this class are immutable. This class also defines static methods for testing whether a particular charset is supported, for locating charset instances by name, and for constructing a map that contains every charset for which support is available in the current Java virtual machine. Support for new charsets can be added via the service-provider interface defined in the CharsetProvider class. All of the methods defined in this class are safe for use by multiple concurrent threads. Charset names Charsets are named by strings composed of the following characters: The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'), The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'), The digits '0' through '9' ('\u0030' through '\u0039'), The dash character '-' ('\u002d', HYPHEN-MINUS), The plus character '+' ('\u002b', PLUS SIGN), The period character '.' ('\u002e', FULL STOP), The colon character ':' ('\u003a', COLON), and The underscore character '_' ('\u005f', LOW LINE). A charset name must begin with either a letter or a digit. The empty string is not a legal charset name. Charset names are not case-sensitive; that is, case is always ignored when comparing charset names. Charset names generally follow the conventions documented in RFC 2278: IANA Charset Registration Procedures. Every charset has a canonical name and may also have one or more aliases. The canonical name is returned by the name method of this class. Canonical names are, by convention, usually in upper case. The aliases of a charset are returned by the aliases method. Some charsets have an historical name that is defined for compatibility with previous versions of the Java platform. A charset's historical name is either its canonical name or one of its aliases. The historical name is returned by the getEncoding() methods of the InputStreamReader and OutputStreamWriter classes. If a charset listed in the IANA Charset Registry is supported by an implementation of the Java platform then its canonical name must be the name listed in the registry. Many charsets are given more than one name in the registry, in which case the registry identifies one of the names as MIME-preferred. If a charset has more than one registry name then its canonical name must be the MIME-preferred name and the other names in the registry must be valid aliases. If a supported charset is not listed in the IANA registry then its canonical name must begin with one of the strings "X-" or "x-". The IANA charset registry does change over time, and so the canonical name and the aliases of a particular charset may also change over time. To ensure compatibility it is recommended that no alias ever be removed from a charset, and that if the canonical name of a charset is changed then its previous canonical name be made into an alias. Standard charsets Every implementation of the Java platform is required to support the following standard charsets. Consult the release documentation for your implementation to see if any other charsets are supported. The behavior of such optional charsets may differ between implementations. CharsetDescription US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 UTF-8 Eight-bit UCS Transformation Format UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark The UTF-8 charset is specified by RFC 2279; the transformation format upon which it is based is specified in Amendment 2 of ISO 10646-1 and is also described in the Unicode Standard. The UTF-16 charsets are specified by RFC 2781; the transformation formats upon which they are based are specified in Amendment 1 of ISO 10646-1 and are also described in the Unicode Standard. The UTF-16 charsets use sixteen-bit quantities and are therefore sensitive to byte order. In these encodings the byte order of a stream may be indicated by an initial byte-order mark represented by the Unicode character '\uFEFF'. Byte-order marks are handled as follows: When decoding, the UTF-16BE and UTF-16LE charsets interpret the initial byte-order marks as a ZERO-WIDTH NON-BREAKING SPACE; when encoding, they do not write byte-order marks. When decoding, the UTF-16 charset interprets the byte-order mark at the beginning of the input stream to indicate the byte-order of the stream but defaults to big-endian if there is no byte-order mark; when encoding, it uses big-endian byte order and writes a big-endian byte-order mark. In any case, byte order marks occurring after the first element of an input sequence are not omitted since the same code is used to represent ZERO-WIDTH NON-BREAKING SPACE. Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system. The StandardCharsets class defines constants for each of the standard charsets. Terminology The name of this class is taken from the terms used in RFC 2278. In that document a charset is defined as the combination of one or more coded character sets and a character-encoding scheme. (This definition is confusing; some other software systems define charset as a synonym for coded character set.) A coded character set is a mapping between a set of abstract characters and a set of integers. US-ASCII, ISO 8859-1, JIS X 0201, and Unicode are examples of coded character sets. Some standards have defined a character set to be simply a set of abstract characters without an associated assigned numbering. An alphabet is an example of such a character set. However, the subtle distinction between character set and coded character set is rarely used in practice; the former has become a short form for the latter, including in the Java API specification. A character-encoding scheme is a mapping between one or more coded character sets and a set of octet (eight-bit byte) sequences. UTF-8, UTF-16, ISO 2022, and EUC are examples of character-encoding schemes. Encoding schemes are often associated with a particular coded character set; UTF-8, for example, is used only to encode Unicode. Some schemes, however, are associated with multiple coded character sets; EUC, for example, can be used to encode characters in a variety of Asian coded character sets. When a coded character set is used exclusively with a single character-encoding scheme then the corresponding charset is usually named for the coded character set; otherwise a charset is usually named for the encoding scheme and, possibly, the locale of the coded character sets that it supports. Hence US-ASCII is both the name of a coded character set and of the charset that encodes it, while EUC-JP is the name of the charset that encodes the JIS X 0201, JIS X 0208, and JIS X 0212 coded character sets for the Japanese language. The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units (that is, sequences of chars) and sequences of bytes.
An engine that can transform a sequence of bytes in a specific charset into a sequence of sixteen-bit Unicode characters.
The input byte sequence is provided in a byte buffer or a series of such buffers. The output character sequence is written to a character buffer or a series of such buffers. A decoder should always be used by making the following sequence of method invocations, hereinafter referred to as a decoding operation:
Reset the decoder via the reset method, unless it has not been used before;
Invoke the decode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
Invoke the decode method one final time, passing true for the endOfInput argument; and then
Invoke the flush method so that the decoder can flush any internal state to the output buffer.
Each invocation of the decode method will decode as many bytes as possible from the input buffer, writing the resulting characters to the output buffer. The decode method returns when more input is required, when there is not enough room in the output buffer, or when a decoding error has occurred. In each case a CoderResult object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from a decoding error, as appropriate, and try again.
There are two general types of decoding errors. If the input byte sequence is not legal for this charset then the input is considered malformed. If the input byte sequence is legal but cannot be mapped to a valid Unicode character then an unmappable character has been encountered.
How a decoding error is handled depends upon the action requested for that type of error, which is described by an instance of the CodingErrorAction class. The possible error actions are to ignore the erroneous input, report the error to the invoker via the returned CoderResult object, or replace the erroneous input with the current value of the replacement string. The replacement
has the initial value "\uFFFD";
its value may be changed via the replaceWith method.
The default action for malformed-input and unmappable-character errors is to report them. The malformed-input error action may be changed via the onMalformedInput method; the unmappable-character action may be changed via the onUnmappableCharacter method.
This class is designed to handle many of the details of the decoding process, including the implementation of error actions. A decoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract decodeLoop method, which encapsulates the basic decoding loop. A subclass that maintains internal state should, additionally, override the implFlush and implReset methods.
Instances of this class are not safe for use by multiple concurrent threads.
An engine that can transform a sequence of bytes in a specific charset into a sequence of sixteen-bit Unicode characters. The input byte sequence is provided in a byte buffer or a series of such buffers. The output character sequence is written to a character buffer or a series of such buffers. A decoder should always be used by making the following sequence of method invocations, hereinafter referred to as a decoding operation: Reset the decoder via the reset method, unless it has not been used before; Invoke the decode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations; Invoke the decode method one final time, passing true for the endOfInput argument; and then Invoke the flush method so that the decoder can flush any internal state to the output buffer. Each invocation of the decode method will decode as many bytes as possible from the input buffer, writing the resulting characters to the output buffer. The decode method returns when more input is required, when there is not enough room in the output buffer, or when a decoding error has occurred. In each case a CoderResult object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from a decoding error, as appropriate, and try again. There are two general types of decoding errors. If the input byte sequence is not legal for this charset then the input is considered malformed. If the input byte sequence is legal but cannot be mapped to a valid Unicode character then an unmappable character has been encountered. How a decoding error is handled depends upon the action requested for that type of error, which is described by an instance of the CodingErrorAction class. The possible error actions are to ignore the erroneous input, report the error to the invoker via the returned CoderResult object, or replace the erroneous input with the current value of the replacement string. The replacement has the initial value "\uFFFD"; its value may be changed via the replaceWith method. The default action for malformed-input and unmappable-character errors is to report them. The malformed-input error action may be changed via the onMalformedInput method; the unmappable-character action may be changed via the onUnmappableCharacter method. This class is designed to handle many of the details of the decoding process, including the implementation of error actions. A decoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract decodeLoop method, which encapsulates the basic decoding loop. A subclass that maintains internal state should, additionally, override the implFlush and implReset methods. Instances of this class are not safe for use by multiple concurrent threads.
An engine that can transform a sequence of sixteen-bit Unicode characters into a sequence of bytes in a specific charset.
The input character sequence is provided in a character buffer or a series of such buffers. The output byte sequence is written to a byte buffer or a series of such buffers. An encoder should always be used by making the following sequence of method invocations, hereinafter referred to as an encoding operation:
Reset the encoder via the reset method, unless it has not been used before;
Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
Invoke the encode method one final time, passing true for the endOfInput argument; and then
Invoke the flush method so that the encoder can flush any internal state to the output buffer.
Each invocation of the encode method will encode as many characters as possible from the input buffer, writing the resulting bytes to the output buffer. The encode method returns when more input is required, when there is not enough room in the output buffer, or when an encoding error has occurred. In each case a CoderResult object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from an encoding error, as appropriate, and try again.
There are two general types of encoding errors. If the input character sequence is not a legal sixteen-bit Unicode sequence then the input is considered malformed. If the input character sequence is legal but cannot be mapped to a valid byte sequence in the given charset then an unmappable character has been encountered.
How an encoding error is handled depends upon the action requested for that type of error, which is described by an instance of the CodingErrorAction class. The possible error actions are to ignore the erroneous input, report the error to the invoker via the returned CoderResult object, or replace the erroneous input with the current value of the replacement byte array. The replacement
is initially set to the encoder's default replacement, which often (but not always) has the initial value { (byte)'?' };
its value may be changed via the replaceWith method.
The default action for malformed-input and unmappable-character errors is to report them. The malformed-input error action may be changed via the onMalformedInput method; the unmappable-character action may be changed via the onUnmappableCharacter method.
This class is designed to handle many of the details of the encoding process, including the implementation of error actions. An encoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract encodeLoop method, which encapsulates the basic encoding loop. A subclass that maintains internal state should, additionally, override the implFlush and implReset methods.
Instances of this class are not safe for use by multiple concurrent threads.
An engine that can transform a sequence of sixteen-bit Unicode characters into a sequence of bytes in a specific charset. The input character sequence is provided in a character buffer or a series of such buffers. The output byte sequence is written to a byte buffer or a series of such buffers. An encoder should always be used by making the following sequence of method invocations, hereinafter referred to as an encoding operation: Reset the encoder via the reset method, unless it has not been used before; Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations; Invoke the encode method one final time, passing true for the endOfInput argument; and then Invoke the flush method so that the encoder can flush any internal state to the output buffer. Each invocation of the encode method will encode as many characters as possible from the input buffer, writing the resulting bytes to the output buffer. The encode method returns when more input is required, when there is not enough room in the output buffer, or when an encoding error has occurred. In each case a CoderResult object is returned to describe the reason for termination. An invoker can examine this object and fill the input buffer, flush the output buffer, or attempt to recover from an encoding error, as appropriate, and try again. There are two general types of encoding errors. If the input character sequence is not a legal sixteen-bit Unicode sequence then the input is considered malformed. If the input character sequence is legal but cannot be mapped to a valid byte sequence in the given charset then an unmappable character has been encountered. How an encoding error is handled depends upon the action requested for that type of error, which is described by an instance of the CodingErrorAction class. The possible error actions are to ignore the erroneous input, report the error to the invoker via the returned CoderResult object, or replace the erroneous input with the current value of the replacement byte array. The replacement is initially set to the encoder's default replacement, which often (but not always) has the initial value { (byte)'?' }; its value may be changed via the replaceWith method. The default action for malformed-input and unmappable-character errors is to report them. The malformed-input error action may be changed via the onMalformedInput method; the unmappable-character action may be changed via the onUnmappableCharacter method. This class is designed to handle many of the details of the encoding process, including the implementation of error actions. An encoder for a specific charset, which is a concrete subclass of this class, need only implement the abstract encodeLoop method, which encapsulates the basic encoding loop. A subclass that maintains internal state should, additionally, override the implFlush and implReset methods. Instances of this class are not safe for use by multiple concurrent threads.
Error thrown when the decodeLoop method of a CharsetDecoder, or the encodeLoop method of a CharsetEncoder, throws an unexpected exception.
Error thrown when the decodeLoop method of a CharsetDecoder, or the encodeLoop method of a CharsetEncoder, throws an unexpected exception.
A description of the result state of a coder.
A charset coder, that is, either a decoder or an encoder, consumes bytes (or characters) from an input buffer, translates them, and writes the resulting characters (or bytes) to an output buffer. A coding process terminates for one of four categories of reasons, which are described by instances of this class:
Underflow is reported when there is no more input to be processed, or there is insufficient input and additional input is required. This condition is represented by the unique result object UNDERFLOW, whose isUnderflow method returns true.
Overflow is reported when there is insufficient room remaining in the output buffer. This condition is represented by the unique result object OVERFLOW, whose isOverflow method returns true.
A malformed-input error is reported when a sequence of input units is not well-formed. Such errors are described by instances of this class whose isMalformed method returns true and whose length method returns the length of the malformed sequence. There is one unique instance of this class for all malformed-input errors of a given length.
An unmappable-character error is reported when a sequence of input units denotes a character that cannot be represented in the output charset. Such errors are described by instances of this class whose isUnmappable method returns true and whose length method returns the length of the input sequence denoting the unmappable character. There is one unique instance of this class for all unmappable-character errors of a given length.
For convenience, the isError method returns true for result objects that describe malformed-input and unmappable-character errors but false for those that describe underflow or overflow conditions.
A description of the result state of a coder. A charset coder, that is, either a decoder or an encoder, consumes bytes (or characters) from an input buffer, translates them, and writes the resulting characters (or bytes) to an output buffer. A coding process terminates for one of four categories of reasons, which are described by instances of this class: Underflow is reported when there is no more input to be processed, or there is insufficient input and additional input is required. This condition is represented by the unique result object UNDERFLOW, whose isUnderflow method returns true. Overflow is reported when there is insufficient room remaining in the output buffer. This condition is represented by the unique result object OVERFLOW, whose isOverflow method returns true. A malformed-input error is reported when a sequence of input units is not well-formed. Such errors are described by instances of this class whose isMalformed method returns true and whose length method returns the length of the malformed sequence. There is one unique instance of this class for all malformed-input errors of a given length. An unmappable-character error is reported when a sequence of input units denotes a character that cannot be represented in the output charset. Such errors are described by instances of this class whose isUnmappable method returns true and whose length method returns the length of the input sequence denoting the unmappable character. There is one unique instance of this class for all unmappable-character errors of a given length. For convenience, the isError method returns true for result objects that describe malformed-input and unmappable-character errors but false for those that describe underflow or overflow conditions.
A typesafe enumeration for coding-error actions.
Instances of this class are used to specify how malformed-input and unmappable-character errors are to be handled by charset decoders and encoders.
A typesafe enumeration for coding-error actions. Instances of this class are used to specify how malformed-input and unmappable-character errors are to be handled by charset decoders and encoders.
No vars found in this namespace.
Unchecked exception thrown when a string that is not a legal charset name is used as such.
Unchecked exception thrown when a string that is not a legal charset name is used as such.
Checked exception thrown when an input byte sequence is not legal for given charset, or an input character sequence is not a legal sixteen-bit Unicode sequence.
Checked exception thrown when an input byte sequence is not legal for given charset, or an input character sequence is not a legal sixteen-bit Unicode sequence.
Charset service-provider class.
A charset provider is a concrete subclass of this class that has a zero-argument constructor and some number of associated charset implementation classes. Charset providers may be installed in an instance of the Java platform as extensions, that is, jar files placed into any of the usual extension directories. Providers may also be made available by adding them to the applet or application class path or by some other platform-specific means. Charset providers are looked up via the current thread's context class loader.
A charset provider identifies itself with a provider-configuration file named java.nio.charset.spi.CharsetProvider in the resource directory META-INF/services. The file should contain a list of fully-qualified concrete charset-provider class names, one per line. A line is terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a line feed. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023'); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8.
If a particular concrete charset provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates will be ignored. The configuration file naming a particular provider need not be in the same jar file or other distribution unit as the provider itself. The provider must be accessible from the same class loader that was initially queried to locate the configuration file; this is not necessarily the class loader that loaded the file.
Charset service-provider class. A charset provider is a concrete subclass of this class that has a zero-argument constructor and some number of associated charset implementation classes. Charset providers may be installed in an instance of the Java platform as extensions, that is, jar files placed into any of the usual extension directories. Providers may also be made available by adding them to the applet or application class path or by some other platform-specific means. Charset providers are looked up via the current thread's context class loader. A charset provider identifies itself with a provider-configuration file named java.nio.charset.spi.CharsetProvider in the resource directory META-INF/services. The file should contain a list of fully-qualified concrete charset-provider class names, one per line. A line is terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a line feed. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023'); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8. If a particular concrete charset provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates will be ignored. The configuration file naming a particular provider need not be in the same jar file or other distribution unit as the provider itself. The provider must be accessible from the same class loader that was initially queried to locate the configuration file; this is not necessarily the class loader that loaded the file.
No vars found in this namespace.
Constant definitions for the standard Charsets. These charsets are guaranteed to be available on every implementation of the Java platform.
Constant definitions for the standard Charsets. These charsets are guaranteed to be available on every implementation of the Java platform.
Checked exception thrown when an input character (or byte) sequence is valid but cannot be mapped to an output byte (or character) sequence.
Checked exception thrown when an input character (or byte) sequence is valid but cannot be mapped to an output byte (or character) sequence.
Unchecked exception thrown when no support is available for a requested charset.
Unchecked exception thrown when no support is available for a requested charset.
No vars found in this namespace.
A double buffer.
This class defines four categories of operations upon double buffers:
Absolute and relative get and put methods that read and write single doubles;
Relative bulk get methods that transfer contiguous sequences of doubles from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of doubles from a double array or some other double buffer into this buffer; and
Methods for compacting, duplicating, and slicing a double buffer.
Double buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing double array into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, a double buffer is either direct or non-direct. A double buffer created via the wrap methods of this class will be non-direct. A double buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a double buffer is direct may be determined by invoking the isDirect method.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
A double buffer. This class defines four categories of operations upon double buffers: Absolute and relative get and put methods that read and write single doubles; Relative bulk get methods that transfer contiguous sequences of doubles from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of doubles from a double array or some other double buffer into this buffer; and Methods for compacting, duplicating, and slicing a double buffer. Double buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing double array into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a double buffer is either direct or non-direct. A double buffer created via the wrap methods of this class will be non-direct. A double buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a double buffer is direct may be determined by invoking the isDirect method. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
Checked exception thrown when a file system operation is denied, typically due to a file permission or other access check.
This exception is not related to the AccessControlException or SecurityException thrown by access controllers or security managers when access to a file is denied.
Checked exception thrown when a file system operation is denied, typically due to a file permission or other access check. This exception is not related to the AccessControlException or SecurityException thrown by access controllers or security managers when access to a file is denied.
Checked exception thrown when a file cannot be moved as an atomic file system operation.
Checked exception thrown when a file cannot be moved as an atomic file system operation.
An entry in an access control list (ACL).
The ACL entry represented by this class is based on the ACL model specified in RFC 3530: Network File System (NFS) version 4 Protocol. Each entry has four components as follows:
The type component determines if the entry
grants or denies access.
The principal component, sometimes called the
"who" component, is a UserPrincipal corresponding to the identity that the entry grants or denies access
The permissions component is a set of
permissions
The flags component is a set of flags to indicate how entries are inherited and propagated
ACL entries are created using an associated AclEntry.Builder object by invoking its build method.
ACL entries are immutable and are safe for use by multiple concurrent threads.
An entry in an access control list (ACL). The ACL entry represented by this class is based on the ACL model specified in RFC 3530: Network File System (NFS) version 4 Protocol. Each entry has four components as follows: The type component determines if the entry grants or denies access. The principal component, sometimes called the "who" component, is a UserPrincipal corresponding to the identity that the entry grants or denies access The permissions component is a set of permissions The flags component is a set of flags to indicate how entries are inherited and propagated ACL entries are created using an associated AclEntry.Builder object by invoking its build method. ACL entries are immutable and are safe for use by multiple concurrent threads.
A builder of AclEntry objects.
A Builder object is obtained by invoking one of the newBuilder methods defined by the AclEntry class.
Builder objects are mutable and are not safe for use by multiple concurrent threads without appropriate synchronization.
A builder of AclEntry objects. A Builder object is obtained by invoking one of the newBuilder methods defined by the AclEntry class. Builder objects are mutable and are not safe for use by multiple concurrent threads without appropriate synchronization.
A file attribute view that supports reading or updating a file's Access Control Lists (ACL) or file owner attributes.
ACLs are used to specify access rights to file system objects. An ACL is an ordered list of access-control-entries, each specifying a UserPrincipal and the level of access for that user principal. This file attribute view defines the getAcl, and setAcl methods to read and write ACLs based on the ACL model specified in RFC 3530: Network File System (NFS) version 4 Protocol. This file attribute view is intended for file system implementations that support the NFSv4 ACL model or have a well-defined mapping between the NFSv4 ACL model and the ACL model used by the file system. The details of such mapping are implementation dependent and are therefore unspecified.
This class also extends FileOwnerAttributeView so as to define methods to get and set the file owner.
When a file system provides access to a set of file-systems that are not homogeneous then only some of the file systems may support ACLs. The supportsFileAttributeView method can be used to test if a file system supports ACLs.
Interoperability
RFC 3530 allows for special user identities to be used on platforms that support the POSIX defined access permissions. The special user identities are "OWNER@", "GROUP@", and "EVERYONE@". When both the AclFileAttributeView and the PosixFileAttributeView are supported then these special user identities may be included in ACL entries that are read or written. The file system's UserPrincipalLookupService may be used to obtain a UserPrincipal to represent these special identities by invoking the lookupPrincipalByName method.
Usage Example: Suppose we wish to add an entry to an existing ACL to grant "joe" access:
// lookup "joe"
UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("joe");
// get view
AclFileAttributeView view = Files.getFileAttributeView(file, AclFileAttributeView.class);
// create ACE to give "joe" read access
AclEntry entry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(joe)
.setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.READ_ATTRIBUTES)
.build();
// read ACL, insert ACE, re-write ACL
List<AclEntry> acl = view.getAcl();
acl.add(0, entry); // insert before any DENY entries
view.setAcl(acl);
Dynamic Access Where dynamic access to file attributes is required, the attributes supported by this attribute view are as follows:
Name
Type
"acl"
List<AclEntry>
"owner"
UserPrincipal
The getAttribute method may be used to read the ACL or owner attributes as if by invoking the getAcl or getOwner methods.
The setAttribute method may be used to update the ACL or owner attributes as if by invoking the setAcl or setOwner methods.
Setting the ACL when creating a file
Implementations supporting this attribute view may also support setting the initial ACL when creating a file or directory. The initial ACL may be provided to methods such as createFile or createDirectory as an FileAttribute with name "acl:acl" and a value that is the list of AclEntry objects.
Where an implementation supports an ACL model that differs from the NFSv4 defined ACL model then setting the initial ACL when creating the file must translate the ACL to the model supported by the file system. Methods that create a file should reject (by throwing IOException) any attempt to create a file that would be less secure as a result of the translation.
A file attribute view that supports reading or updating a file's Access Control Lists (ACL) or file owner attributes. ACLs are used to specify access rights to file system objects. An ACL is an ordered list of access-control-entries, each specifying a UserPrincipal and the level of access for that user principal. This file attribute view defines the getAcl, and setAcl methods to read and write ACLs based on the ACL model specified in RFC 3530: Network File System (NFS) version 4 Protocol. This file attribute view is intended for file system implementations that support the NFSv4 ACL model or have a well-defined mapping between the NFSv4 ACL model and the ACL model used by the file system. The details of such mapping are implementation dependent and are therefore unspecified. This class also extends FileOwnerAttributeView so as to define methods to get and set the file owner. When a file system provides access to a set of file-systems that are not homogeneous then only some of the file systems may support ACLs. The supportsFileAttributeView method can be used to test if a file system supports ACLs. Interoperability RFC 3530 allows for special user identities to be used on platforms that support the POSIX defined access permissions. The special user identities are "OWNER@", "GROUP@", and "EVERYONE@". When both the AclFileAttributeView and the PosixFileAttributeView are supported then these special user identities may be included in ACL entries that are read or written. The file system's UserPrincipalLookupService may be used to obtain a UserPrincipal to represent these special identities by invoking the lookupPrincipalByName method. Usage Example: Suppose we wish to add an entry to an existing ACL to grant "joe" access: // lookup "joe" UserPrincipal joe = file.getFileSystem().getUserPrincipalLookupService() .lookupPrincipalByName("joe"); // get view AclFileAttributeView view = Files.getFileAttributeView(file, AclFileAttributeView.class); // create ACE to give "joe" read access AclEntry entry = AclEntry.newBuilder() .setType(AclEntryType.ALLOW) .setPrincipal(joe) .setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.READ_ATTRIBUTES) .build(); // read ACL, insert ACE, re-write ACL List<AclEntry> acl = view.getAcl(); acl.add(0, entry); // insert before any DENY entries view.setAcl(acl); Dynamic Access Where dynamic access to file attributes is required, the attributes supported by this attribute view are as follows: Name Type "acl" List<AclEntry> "owner" UserPrincipal The getAttribute method may be used to read the ACL or owner attributes as if by invoking the getAcl or getOwner methods. The setAttribute method may be used to update the ACL or owner attributes as if by invoking the setAcl or setOwner methods. Setting the ACL when creating a file Implementations supporting this attribute view may also support setting the initial ACL when creating a file or directory. The initial ACL may be provided to methods such as createFile or createDirectory as an FileAttribute with name "acl:acl" and a value that is the list of AclEntry objects. Where an implementation supports an ACL model that differs from the NFSv4 defined ACL model then setting the initial ACL when creating the file must translate the ACL to the model supported by the file system. Methods that create a file should reject (by throwing IOException) any attempt to create a file that would be less secure as a result of the translation.
An object that provides a read-only or updatable view of non-opaque values associated with an object in a filesystem. This interface is extended or implemented by specific attribute views that define the attributes supported by the view. A specific attribute view will typically define type-safe methods to read or update the attributes that it supports.
An object that provides a read-only or updatable view of non-opaque values associated with an object in a filesystem. This interface is extended or implemented by specific attribute views that define the attributes supported by the view. A specific attribute view will typically define type-safe methods to read or update the attributes that it supports.
Basic attributes associated with a file in a file system.
Basic file attributes are attributes that are common to many file systems and consist of mandatory and optional file attributes as defined by this interface.
Usage Example:
Path file = ... BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
Basic attributes associated with a file in a file system. Basic file attributes are attributes that are common to many file systems and consist of mandatory and optional file attributes as defined by this interface. Usage Example: Path file = ... BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
A file attribute view that provides a view of a basic set of file attributes common to many file systems. The basic set of file attributes consist of mandatory and optional file attributes as defined by the BasicFileAttributes interface.
The file attributes are retrieved from the file system as a bulk operation by invoking the readAttributes method. This class also defines the setTimes method to update the file's time attributes.
Where dynamic access to file attributes is required, the attributes supported by this attribute view have the following names and types:
Name
Type
"lastModifiedTime"
FileTime
"lastAccessTime"
FileTime
"creationTime"
FileTime
"size"
Long
"isRegularFile"
Boolean
"isDirectory"
Boolean
"isSymbolicLink"
Boolean
"isOther"
Boolean
"fileKey"
Object
The getAttribute method may be used to read any of these attributes as if by invoking the readAttributes() method.
The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as if by invoking the setTimes method.
A file attribute view that provides a view of a basic set of file attributes common to many file systems. The basic set of file attributes consist of mandatory and optional file attributes as defined by the BasicFileAttributes interface. The file attributes are retrieved from the file system as a bulk operation by invoking the readAttributes method. This class also defines the setTimes method to update the file's time attributes. Where dynamic access to file attributes is required, the attributes supported by this attribute view have the following names and types: Name Type "lastModifiedTime" FileTime "lastAccessTime" FileTime "creationTime" FileTime "size" Long "isRegularFile" Boolean "isDirectory" Boolean "isSymbolicLink" Boolean "isOther" Boolean "fileKey" Object The getAttribute method may be used to read any of these attributes as if by invoking the readAttributes() method. The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as if by invoking the setTimes method.
No vars found in this namespace.
File attributes associated with a file in a file system that supports legacy "DOS" attributes.
Usage Example:
Path file = ... DosFileAttributes attrs = Files.readAttributes(file, DosFileAttributes.class);
File attributes associated with a file in a file system that supports legacy "DOS" attributes. Usage Example: Path file = ... DosFileAttributes attrs = Files.readAttributes(file, DosFileAttributes.class);
A file attribute view that provides a view of the legacy "DOS" file attributes. These attributes are supported by file systems such as the File Allocation Table (FAT) format commonly used in consumer devices.
A DosFileAttributeView is a BasicFileAttributeView that additionally supports access to the set of DOS attribute flags that are used to indicate if the file is read-only, hidden, a system file, or archived.
Where dynamic access to file attributes is required, the attributes supported by this attribute view are as defined by BasicFileAttributeView, and in addition, the following attributes are supported:
Name
Type
readonly
Boolean
hidden
Boolean
system
Boolean
archive
Boolean
The getAttribute method may be used to read any of these attributes, or any of the attributes defined by BasicFileAttributeView as if by invoking the readAttributes() method.
The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as defined by BasicFileAttributeView. It may also be used to update the DOS attributes as if by invoking the setReadOnly, setHidden, setSystem, and setArchive methods respectively.
A file attribute view that provides a view of the legacy "DOS" file attributes. These attributes are supported by file systems such as the File Allocation Table (FAT) format commonly used in consumer devices. A DosFileAttributeView is a BasicFileAttributeView that additionally supports access to the set of DOS attribute flags that are used to indicate if the file is read-only, hidden, a system file, or archived. Where dynamic access to file attributes is required, the attributes supported by this attribute view are as defined by BasicFileAttributeView, and in addition, the following attributes are supported: Name Type readonly Boolean hidden Boolean system Boolean archive Boolean The getAttribute method may be used to read any of these attributes, or any of the attributes defined by BasicFileAttributeView as if by invoking the readAttributes() method. The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as defined by BasicFileAttributeView. It may also be used to update the DOS attributes as if by invoking the setReadOnly, setHidden, setSystem, and setArchive methods respectively.
An object that encapsulates the value of a file attribute that can be set atomically when creating a new file or directory by invoking the createFile or createDirectory methods.
An object that encapsulates the value of a file attribute that can be set atomically when creating a new file or directory by invoking the createFile or createDirectory methods.
An attribute view that is a read-only or updatable view of non-opaque values associated with a file in a filesystem. This interface is extended or implemented by specific file attribute views that define methods to read and/or update the attributes of a file.
An attribute view that is a read-only or updatable view of non-opaque values associated with a file in a filesystem. This interface is extended or implemented by specific file attribute views that define methods to read and/or update the attributes of a file.
No vars found in this namespace.
A file attribute view that supports reading or updating the owner of a file. This file attribute view is intended for file system implementations that support a file attribute that represents an identity that is the owner of the file. Often the owner of a file is the identity of the entity that created the file.
The getOwner or setOwner methods may be used to read or update the owner of the file.
The getAttribute and setAttribute methods may also be used to read or update the owner. In that case, the owner attribute is identified by the name "owner", and the value of the attribute is a UserPrincipal.
A file attribute view that supports reading or updating the owner of a file. This file attribute view is intended for file system implementations that support a file attribute that represents an identity that is the owner of the file. Often the owner of a file is the identity of the entity that created the file. The getOwner or setOwner methods may be used to read or update the owner of the file. The getAttribute and setAttribute methods may also be used to read or update the owner. In that case, the owner attribute is identified by the name "owner", and the value of the attribute is a UserPrincipal.
An attribute view that is a read-only or updatable view of the attributes of a FileStore.
An attribute view that is a read-only or updatable view of the attributes of a FileStore.
No vars found in this namespace.
Represents the value of a file's time stamp attribute. For example, it may represent the time that the file was last modified, accessed, or created.
Instances of this class are immutable.
Represents the value of a file's time stamp attribute. For example, it may represent the time that the file was last modified, accessed, or created. Instances of this class are immutable.
A UserPrincipal representing a group identity, used to determine access rights to objects in a file system. The exact definition of a group is implementation specific, but typically, it represents an identity created for administrative purposes so as to determine the access rights for the members of the group. Whether an entity can be a member of multiple groups, and whether groups can be nested, are implementation specified and therefore not specified.
A UserPrincipal representing a group identity, used to determine access rights to objects in a file system. The exact definition of a group is implementation specific, but typically, it represents an identity created for administrative purposes so as to determine the access rights for the members of the group. Whether an entity can be a member of multiple groups, and whether groups can be nested, are implementation specified and therefore not specified.
No vars found in this namespace.
File attributes associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
The POSIX attributes of a file are retrieved using a PosixFileAttributeView by invoking its readAttributes method.
File attributes associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards. The POSIX attributes of a file are retrieved using a PosixFileAttributeView by invoking its readAttributes method.
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
Operating systems that implement the POSIX family of standards commonly use file systems that have a file owner, group-owner, and related access permissions. This file attribute view provides read and write access to these attributes.
The readAttributes method is used to read the file's attributes. The file owner is represented by a UserPrincipal that is the identity of the file owner for the purposes of access control. The group-owner, represented by a GroupPrincipal, is the identity of the group owner, where a group is an identity created for administrative purposes so as to determine the access rights for the members of the group.
The permissions attribute is a set of access permissions. This file attribute view provides access to the nine permission defined by the PosixFilePermission class. These nine permission bits determine the read, write, and execute access for the file owner, group, and others (others meaning identities other than the owner and members of the group). Some operating systems and file systems may provide additional permission bits but access to these other bits is not defined by this class in this release.
Usage Example: Suppose we need to print out the owner and access permissions of a file:
Path file = ...
PosixFileAttributes attrs = Files.getFileAttributeView(file, PosixFileAttributeView.class)
.readAttributes();
System.out.format("%s %s%n",
attrs.owner().getName(),
PosixFilePermissions.toString(attrs.permissions()));
Dynamic Access Where dynamic access to file attributes is required, the attributes supported by this attribute view are as defined by BasicFileAttributeView and FileOwnerAttributeView, and in addition, the following attributes are supported:
Name
Type
"permissions"
Set<PosixFilePermission>
"group"
GroupPrincipal
The getAttribute method may be used to read any of these attributes, or any of the attributes defined by BasicFileAttributeView as if by invoking the readAttributes() method.
The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as defined by BasicFileAttributeView. It may also be used to update the permissions, owner, or group-owner as if by invoking the setPermissions, setOwner, and setGroup methods respectively.
Setting Initial Permissions Implementations supporting this attribute view may also support setting the initial permissions when creating a file or directory. The initial permissions are provided to the createFile or createDirectory methods as a FileAttribute with name "posix:permissions" and a value that is the set of permissions. The following example uses the asFileAttribute method to construct a FileAttribute when creating a file:
Path path = ...
Set<PosixFilePermission> perms =
EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ);
Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));
When the access permissions are set at file creation time then the actual value of the permissions may differ that the value of the attribute object. The reasons for this are implementation specific. On UNIX systems, for example, a process has a umask that impacts the permission bits of newly created files. Where an implementation supports the setting of the access permissions, and the underlying file system supports access permissions, then it is required that the value of the actual access permissions will be equal or less than the value of the attribute provided to the createFile or createDirectory methods. In other words, the file may be more secure than requested.
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards. Operating systems that implement the POSIX family of standards commonly use file systems that have a file owner, group-owner, and related access permissions. This file attribute view provides read and write access to these attributes. The readAttributes method is used to read the file's attributes. The file owner is represented by a UserPrincipal that is the identity of the file owner for the purposes of access control. The group-owner, represented by a GroupPrincipal, is the identity of the group owner, where a group is an identity created for administrative purposes so as to determine the access rights for the members of the group. The permissions attribute is a set of access permissions. This file attribute view provides access to the nine permission defined by the PosixFilePermission class. These nine permission bits determine the read, write, and execute access for the file owner, group, and others (others meaning identities other than the owner and members of the group). Some operating systems and file systems may provide additional permission bits but access to these other bits is not defined by this class in this release. Usage Example: Suppose we need to print out the owner and access permissions of a file: Path file = ... PosixFileAttributes attrs = Files.getFileAttributeView(file, PosixFileAttributeView.class) .readAttributes(); System.out.format("%s %s%n", attrs.owner().getName(), PosixFilePermissions.toString(attrs.permissions())); Dynamic Access Where dynamic access to file attributes is required, the attributes supported by this attribute view are as defined by BasicFileAttributeView and FileOwnerAttributeView, and in addition, the following attributes are supported: Name Type "permissions" Set<PosixFilePermission> "group" GroupPrincipal The getAttribute method may be used to read any of these attributes, or any of the attributes defined by BasicFileAttributeView as if by invoking the readAttributes() method. The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as defined by BasicFileAttributeView. It may also be used to update the permissions, owner, or group-owner as if by invoking the setPermissions, setOwner, and setGroup methods respectively. Setting Initial Permissions Implementations supporting this attribute view may also support setting the initial permissions when creating a file or directory. The initial permissions are provided to the createFile or createDirectory methods as a FileAttribute with name "posix:permissions" and a value that is the set of permissions. The following example uses the asFileAttribute method to construct a FileAttribute when creating a file: Path path = ... Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ); Files.createFile(path, PosixFilePermissions.asFileAttribute(perms)); When the access permissions are set at file creation time then the actual value of the permissions may differ that the value of the attribute object. The reasons for this are implementation specific. On UNIX systems, for example, a process has a umask that impacts the permission bits of newly created files. Where an implementation supports the setting of the access permissions, and the underlying file system supports access permissions, then it is required that the value of the actual access permissions will be equal or less than the value of the attribute provided to the createFile or createDirectory methods. In other words, the file may be more secure than requested.
This class consists exclusively of static methods that operate on sets of PosixFilePermission objects.
This class consists exclusively of static methods that operate on sets of PosixFilePermission objects.
A file attribute view that provides a view of a file's user-defined attributes, sometimes known as extended attributes. User-defined file attributes are used to store metadata with a file that is not meaningful to the file system. It is primarily intended for file system implementations that support such a capability directly but may be emulated. The details of such emulation are highly implementation specific and therefore not specified.
This FileAttributeView provides a view of a file's user-defined attributes as a set of name/value pairs, where the attribute name is represented by a String. An implementation may require to encode and decode from the platform or file system representation when accessing the attribute. The value has opaque content. This attribute view defines the read and write methods to read the value into or write from a ByteBuffer. This FileAttributeView is not intended for use where the size of an attribute value is larger than Integer.MAX_VALUE.
User-defined attributes may be used in some implementations to store security related attributes so consequently, in the case of the default provider at least, all methods that access user-defined attributes require the RuntimePermission("accessUserDefinedAttributes") permission when a security manager is installed.
The supportsFileAttributeView method may be used to test if a specific FileStore supports the storage of user-defined attributes.
Where dynamic access to file attributes is required, the getAttribute method may be used to read the attribute value. The attribute value is returned as a byte array (byte[]). The setAttribute method may be used to write the value of a user-defined attribute from a buffer (as if by invoking the write method), or byte array (byte[]).
A file attribute view that provides a view of a file's user-defined attributes, sometimes known as extended attributes. User-defined file attributes are used to store metadata with a file that is not meaningful to the file system. It is primarily intended for file system implementations that support such a capability directly but may be emulated. The details of such emulation are highly implementation specific and therefore not specified. This FileAttributeView provides a view of a file's user-defined attributes as a set of name/value pairs, where the attribute name is represented by a String. An implementation may require to encode and decode from the platform or file system representation when accessing the attribute. The value has opaque content. This attribute view defines the read and write methods to read the value into or write from a ByteBuffer. This FileAttributeView is not intended for use where the size of an attribute value is larger than Integer.MAX_VALUE. User-defined attributes may be used in some implementations to store security related attributes so consequently, in the case of the default provider at least, all methods that access user-defined attributes require the RuntimePermission("accessUserDefinedAttributes") permission when a security manager is installed. The supportsFileAttributeView method may be used to test if a specific FileStore supports the storage of user-defined attributes. Where dynamic access to file attributes is required, the getAttribute method may be used to read the attribute value. The attribute value is returned as a byte array (byte[]). The setAttribute method may be used to write the value of a user-defined attribute from a buffer (as if by invoking the write method), or byte array (byte[]).
A Principal representing an identity used to determine access rights to objects in a file system.
On many platforms and file systems an entity requires appropriate access rights or permissions in order to access objects in a file system. The access rights are generally performed by checking the identity of the entity. For example, on implementations that use Access Control Lists (ACLs) to enforce privilege separation then a file in the file system may have an associated ACL that determines the access rights of identities specified in the ACL.
A UserPrincipal object is an abstract representation of an identity. It has a name that is typically the username or account name that it represents. User principal objects may be obtained using a UserPrincipalLookupService, or returned by FileAttributeView implementations that provide access to identity related attributes. For example, the AclFileAttributeView and PosixFileAttributeView provide access to a file's owner.
A Principal representing an identity used to determine access rights to objects in a file system. On many platforms and file systems an entity requires appropriate access rights or permissions in order to access objects in a file system. The access rights are generally performed by checking the identity of the entity. For example, on implementations that use Access Control Lists (ACLs) to enforce privilege separation then a file in the file system may have an associated ACL that determines the access rights of identities specified in the ACL. A UserPrincipal object is an abstract representation of an identity. It has a name that is typically the username or account name that it represents. User principal objects may be obtained using a UserPrincipalLookupService, or returned by FileAttributeView implementations that provide access to identity related attributes. For example, the AclFileAttributeView and PosixFileAttributeView provide access to a file's owner.
No vars found in this namespace.
An object to lookup user and group principals by name. A UserPrincipal represents an identity that may be used to determine access rights to objects in a file system. A GroupPrincipal represents a group identity. A UserPrincipalLookupService defines methods to lookup identities by name or group name (which are typically user or account names). Whether names and group names are case sensitive or not depends on the implementation. The exact definition of a group is implementation specific but typically a group represents an identity created for administrative purposes so as to determine the access rights for the members of the group. In particular it is implementation specific if the namespace for names and groups is the same or is distinct. To ensure consistent and correct behavior across platforms it is recommended that this API be used as if the namespaces are distinct. In other words, the lookupPrincipalByName should be used to lookup users, and lookupPrincipalByGroupName should be used to lookup groups.
An object to lookup user and group principals by name. A UserPrincipal represents an identity that may be used to determine access rights to objects in a file system. A GroupPrincipal represents a group identity. A UserPrincipalLookupService defines methods to lookup identities by name or group name (which are typically user or account names). Whether names and group names are case sensitive or not depends on the implementation. The exact definition of a group is implementation specific but typically a group represents an identity created for administrative purposes so as to determine the access rights for the members of the group. In particular it is implementation specific if the namespace for names and groups is the same or is distinct. To ensure consistent and correct behavior across platforms it is recommended that this API be used as if the namespaces are distinct. In other words, the lookupPrincipalByName should be used to lookup users, and lookupPrincipalByGroupName should be used to lookup groups.
Checked exception thrown when a lookup of UserPrincipal fails because the principal does not exist.
Checked exception thrown when a lookup of UserPrincipal fails because the principal does not exist.
Unchecked exception thrown when an attempt is made to invoke an operation on a directory stream that is closed.
Unchecked exception thrown when an attempt is made to invoke an operation on a directory stream that is closed.
Unchecked exception thrown when an attempt is made to invoke an operation on a file and the file system is closed.
Unchecked exception thrown when an attempt is made to invoke an operation on a file and the file system is closed.
Unchecked exception thrown when an attempt is made to invoke an operation on a watch service that is closed.
Unchecked exception thrown when an attempt is made to invoke an operation on a watch service that is closed.
An object that configures how to copy or move a file.
Objects of this type may be used with the Files.copy(Path,Path,CopyOption...), Files.copy(InputStream,Path,CopyOption...) and Files.move(Path,Path,CopyOption...) methods to configure how a file is copied or moved.
The StandardCopyOption enumeration type defines the standard options.
An object that configures how to copy or move a file. Objects of this type may be used with the Files.copy(Path,Path,CopyOption...), Files.copy(InputStream,Path,CopyOption...) and Files.move(Path,Path,CopyOption...) methods to configure how a file is copied or moved. The StandardCopyOption enumeration type defines the standard options.
No vars found in this namespace.
No vars found in this namespace.
Runtime exception thrown if an I/O error is encountered when iterating over the entries in a directory. The I/O error is retrieved as an IOException using the getCause() method.
Runtime exception thrown if an I/O error is encountered when iterating over the entries in a directory. The I/O error is retrieved as an IOException using the getCause() method.
Checked exception thrown when a file system operation fails because a directory is not empty.
Checked exception thrown when a file system operation fails because a directory is not empty.
An object to iterate over the entries in a directory. A directory stream allows for the convenient use of the for-each construct to iterate over a directory.
While DirectoryStream extends Iterable, it is not a general-purpose Iterable as it supports only a single Iterator; invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.
An important property of the directory stream's Iterator is that its hasNext method is guaranteed to read-ahead by at least one element. If hasNext method returns true, and is followed by a call to the next method, it is guaranteed that the next method will not throw an exception due to an I/O error, or because the stream has been closed. The Iterator does not support the remove operation.
A DirectoryStream is opened upon creation and is closed by invoking the close method. Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed:
Path dir = ... try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry: stream) { ... } }
Once a directory stream is closed, then further access to the directory, using the Iterator, behaves as if the end of stream has been reached. Due to read-ahead, the Iterator may return one or more elements after the directory stream has been closed. Once these buffered elements have been read, then subsequent calls to the hasNext method returns false, and subsequent calls to the next method will throw NoSuchElementException.
A directory stream is not required to be asynchronously closeable. If a thread is blocked on the directory stream's iterator reading from the directory, and another thread invokes the close method, then the second thread may block until the read operation is complete.
If an I/O error is encountered when accessing the directory then it causes the Iterator's hasNext or next methods to throw DirectoryIteratorException with the IOException as the cause. As stated above, the hasNext method is guaranteed to read-ahead by at least one element. This means that if hasNext method returns true, and is followed by a call to the next method, then it is guaranteed that the next method will not fail with a DirectoryIteratorException.
The elements returned by the iterator are in no specific order. Some file systems maintain special links to the directory itself and the directory's parent directory. Entries representing these links are not returned by the iterator.
The iterator is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after the DirectoryStream is created.
Usage Examples: Suppose we want a list of the source files in a directory. This example uses both the for-each and try-with-resources constructs.
List<Path> listSourceFiles(Path dir) throws IOException { List<Path> result = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) { for (Path entry: stream) { result.add(entry); } } catch (DirectoryIteratorException ex) { // I/O error encounted during the iteration, the cause is an IOException throw ex.getCause(); } return result; }
An object to iterate over the entries in a directory. A directory stream allows for the convenient use of the for-each construct to iterate over a directory. While DirectoryStream extends Iterable, it is not a general-purpose Iterable as it supports only a single Iterator; invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException. An important property of the directory stream's Iterator is that its hasNext method is guaranteed to read-ahead by at least one element. If hasNext method returns true, and is followed by a call to the next method, it is guaranteed that the next method will not throw an exception due to an I/O error, or because the stream has been closed. The Iterator does not support the remove operation. A DirectoryStream is opened upon creation and is closed by invoking the close method. Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed: Path dir = ... try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry: stream) { ... } } Once a directory stream is closed, then further access to the directory, using the Iterator, behaves as if the end of stream has been reached. Due to read-ahead, the Iterator may return one or more elements after the directory stream has been closed. Once these buffered elements have been read, then subsequent calls to the hasNext method returns false, and subsequent calls to the next method will throw NoSuchElementException. A directory stream is not required to be asynchronously closeable. If a thread is blocked on the directory stream's iterator reading from the directory, and another thread invokes the close method, then the second thread may block until the read operation is complete. If an I/O error is encountered when accessing the directory then it causes the Iterator's hasNext or next methods to throw DirectoryIteratorException with the IOException as the cause. As stated above, the hasNext method is guaranteed to read-ahead by at least one element. This means that if hasNext method returns true, and is followed by a call to the next method, then it is guaranteed that the next method will not fail with a DirectoryIteratorException. The elements returned by the iterator are in no specific order. Some file systems maintain special links to the directory itself and the directory's parent directory. Entries representing these links are not returned by the iterator. The iterator is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after the DirectoryStream is created. Usage Examples: Suppose we want a list of the source files in a directory. This example uses both the for-each and try-with-resources constructs. List<Path> listSourceFiles(Path dir) throws IOException { List<Path> result = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) { for (Path entry: stream) { result.add(entry); } } catch (DirectoryIteratorException ex) { // I/O error encounted during the iteration, the cause is an IOException throw ex.getCause(); } return result; }
An interface that is implemented by objects that decide if a directory entry should be accepted or filtered. A Filter is passed as the parameter to the Files.newDirectoryStream(Path,DirectoryStream.Filter) method when opening a directory to iterate over the entries in the directory.
An interface that is implemented by objects that decide if a directory entry should be accepted or filtered. A Filter is passed as the parameter to the Files.newDirectoryStream(Path,DirectoryStream.Filter) method when opening a directory to iterate over the entries in the directory.
Checked exception thrown when an attempt is made to create a file or directory and a file of that name already exists.
Checked exception thrown when an attempt is made to create a file or directory and a file of that name already exists.
This class consists exclusively of static methods that operate on files, directories, or other types of files.
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
This class consists exclusively of static methods that operate on files, directories, or other types of files. In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
Storage for files. A FileStore represents a storage pool, device, partition, volume, concrete file system or other implementation specific means of file storage. The FileStore for where a file is stored is obtained by invoking the getFileStore method, or all file stores can be enumerated by invoking the getFileStores method.
In addition to the methods defined by this class, a file store may support one or more FileStoreAttributeView classes that provide a read-only or updatable view of a set of file store attributes.
Storage for files. A FileStore represents a storage pool, device, partition, volume, concrete file system or other implementation specific means of file storage. The FileStore for where a file is stored is obtained by invoking the getFileStore method, or all file stores can be enumerated by invoking the getFileStores method. In addition to the methods defined by this class, a file store may support one or more FileStoreAttributeView classes that provide a read-only or updatable view of a set of file store attributes.
Provides an interface to a file system and is the factory for objects to access files and other objects in the file system.
The default file system, obtained by invoking the FileSystems.getDefault method, provides access to the file system that is accessible to the Java virtual machine. The FileSystems class defines methods to create file systems that provide access to other types of (custom) file systems.
A file system is the factory for several types of objects:
The getPath method converts a system dependent path string, returning a Path object that may be used to locate and access a file. The getPathMatcher method is used to create a PathMatcher that performs match operations on paths. The getFileStores method returns an iterator over the underlying file-stores. The getUserPrincipalLookupService method returns the UserPrincipalLookupService to lookup users or groups by name. The newWatchService method creates a WatchService that may be used to watch objects for changes and events.
File systems vary greatly. In some cases the file system is a single hierarchy of files with one top-level root directory. In other cases it may have several distinct file hierarchies, each with its own top-level root directory. The getRootDirectories method may be used to iterate over the root directories in the file system. A file system is typically composed of one or more underlying file-stores that provide the storage for the files. Theses file stores can also vary in the features they support, and the file attributes or meta-data that they associate with files.
A file system is open upon creation and can be closed by invoking its close method. Once closed, any further attempt to access objects in the file system cause ClosedFileSystemException to be thrown. File systems created by the default provider cannot be closed.
A FileSystem can provide read-only or read-write access to the file system. Whether or not a file system provides read-only access is established when the FileSystem is created and can be tested by invoking its isReadOnly method. Attempts to write to file stores by means of an object associated with a read-only file system throws ReadOnlyFileSystemException.
File systems are safe for use by multiple concurrent threads. The close method may be invoked at any time to close a file system but whether a file system is asynchronously closeable is provider specific and therefore unspecified. In other words, if a thread is accessing an object in a file system, and another thread invokes the close method then it may require to block until the first operation is complete. Closing a file system causes all open channels, watch services, and other closeable objects associated with the file system to be closed.
Provides an interface to a file system and is the factory for objects to access files and other objects in the file system. The default file system, obtained by invoking the FileSystems.getDefault method, provides access to the file system that is accessible to the Java virtual machine. The FileSystems class defines methods to create file systems that provide access to other types of (custom) file systems. A file system is the factory for several types of objects: The getPath method converts a system dependent path string, returning a Path object that may be used to locate and access a file. The getPathMatcher method is used to create a PathMatcher that performs match operations on paths. The getFileStores method returns an iterator over the underlying file-stores. The getUserPrincipalLookupService method returns the UserPrincipalLookupService to lookup users or groups by name. The newWatchService method creates a WatchService that may be used to watch objects for changes and events. File systems vary greatly. In some cases the file system is a single hierarchy of files with one top-level root directory. In other cases it may have several distinct file hierarchies, each with its own top-level root directory. The getRootDirectories method may be used to iterate over the root directories in the file system. A file system is typically composed of one or more underlying file-stores that provide the storage for the files. Theses file stores can also vary in the features they support, and the file attributes or meta-data that they associate with files. A file system is open upon creation and can be closed by invoking its close method. Once closed, any further attempt to access objects in the file system cause ClosedFileSystemException to be thrown. File systems created by the default provider cannot be closed. A FileSystem can provide read-only or read-write access to the file system. Whether or not a file system provides read-only access is established when the FileSystem is created and can be tested by invoking its isReadOnly method. Attempts to write to file stores by means of an object associated with a read-only file system throws ReadOnlyFileSystemException. File systems are safe for use by multiple concurrent threads. The close method may be invoked at any time to close a file system but whether a file system is asynchronously closeable is provider specific and therefore unspecified. In other words, if a thread is accessing an object in a file system, and another thread invokes the close method then it may require to block until the first operation is complete. Closing a file system causes all open channels, watch services, and other closeable objects associated with the file system to be closed.
Runtime exception thrown when an attempt is made to create a file system that already exists.
Runtime exception thrown when an attempt is made to create a file system that already exists.
Thrown when a file system operation fails on one or two files. This class is the general class for file system exceptions.
Thrown when a file system operation fails on one or two files. This class is the general class for file system exceptions.
Checked exception thrown when a file system loop, or cycle, is encountered.
Checked exception thrown when a file system loop, or cycle, is encountered.
Runtime exception thrown when a file system cannot be found.
Runtime exception thrown when a file system cannot be found.
Factory methods for file systems. This class defines the getDefault method to get the default file system and factory methods to construct other types of file systems.
The first invocation of any of the methods defined by this class causes the default provider to be loaded. The default provider, identified by the URI scheme "file", creates the FileSystem that provides access to the file systems accessible to the Java virtual machine. If the process of loading or initializing the default provider fails then an unspecified error is thrown.
The first invocation of the installedProviders method, by way of invoking any of the newFileSystem methods defined by this class, locates and loads all installed file system providers. Installed providers are loaded using the service-provider loading facility defined by the ServiceLoader class. Installed providers are loaded using the system class loader. If the system class loader cannot be found then the extension class loader is used; if there is no extension class loader then the bootstrap class loader is used. Providers are typically installed by placing them in a JAR file on the application class path or in the extension directory, the JAR file contains a provider-configuration file named java.nio.file.spi.FileSystemProvider in the resource directory META-INF/services, and the file lists one or more fully-qualified names of concrete subclass of FileSystemProvider that have a zero argument constructor. The ordering that installed providers are located is implementation specific. If a provider is instantiated and its getScheme returns the same URI scheme of a provider that was previously instantiated then the most recently instantiated duplicate is discarded. URI schemes are compared without regard to case. During construction a provider may safely access files associated with the default provider but care needs to be taken to avoid circular loading of other installed providers. If circular loading of installed providers is detected then an unspecified error is thrown.
This class also defines factory methods that allow a ClassLoader to be specified when locating a provider. As with installed providers, the provider classes are identified by placing the provider configuration file in the resource directory META-INF/services.
If a thread initiates the loading of the installed file system providers and another thread invokes a method that also attempts to load the providers then the method will block until the loading completes.
Factory methods for file systems. This class defines the getDefault method to get the default file system and factory methods to construct other types of file systems. The first invocation of any of the methods defined by this class causes the default provider to be loaded. The default provider, identified by the URI scheme "file", creates the FileSystem that provides access to the file systems accessible to the Java virtual machine. If the process of loading or initializing the default provider fails then an unspecified error is thrown. The first invocation of the installedProviders method, by way of invoking any of the newFileSystem methods defined by this class, locates and loads all installed file system providers. Installed providers are loaded using the service-provider loading facility defined by the ServiceLoader class. Installed providers are loaded using the system class loader. If the system class loader cannot be found then the extension class loader is used; if there is no extension class loader then the bootstrap class loader is used. Providers are typically installed by placing them in a JAR file on the application class path or in the extension directory, the JAR file contains a provider-configuration file named java.nio.file.spi.FileSystemProvider in the resource directory META-INF/services, and the file lists one or more fully-qualified names of concrete subclass of FileSystemProvider that have a zero argument constructor. The ordering that installed providers are located is implementation specific. If a provider is instantiated and its getScheme returns the same URI scheme of a provider that was previously instantiated then the most recently instantiated duplicate is discarded. URI schemes are compared without regard to case. During construction a provider may safely access files associated with the default provider but care needs to be taken to avoid circular loading of other installed providers. If circular loading of installed providers is detected then an unspecified error is thrown. This class also defines factory methods that allow a ClassLoader to be specified when locating a provider. As with installed providers, the provider classes are identified by placing the provider configuration file in the resource directory META-INF/services. If a thread initiates the loading of the installed file system providers and another thread invokes a method that also attempts to load the providers then the method will block until the loading completes.
A visitor of files. An implementation of this interface is provided to the Files.walkFileTree methods to visit each file in a file tree.
Usage Examples: Suppose we want to delete a file tree. In that case, each directory should be deleted after the entries in the directory are deleted.
Path start = ...
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e)
throws IOException
{
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed
throw e;
}
}
});
Furthermore, suppose we want to copy a file tree to a target location. In that case, symbolic links should be followed and the target directory should be created before the entries in the directory are copied.
final Path source = ...
final Path target = ...
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
Path targetdir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, targetdir);
} catch (FileAlreadyExistsException e) {
if (!Files.isDirectory(targetdir))
throw e;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.copy(file, target.resolve(source.relativize(file)));
return CONTINUE;
}
});
A visitor of files. An implementation of this interface is provided to the Files.walkFileTree methods to visit each file in a file tree. Usage Examples: Suppose we want to delete a file tree. In that case, each directory should be deleted after the entries in the directory are deleted. Path start = ... Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } } }); Furthermore, suppose we want to copy a file tree to a target location. In that case, symbolic links should be followed and the target directory should be created before the entries in the directory are copied. final Path source = ... final Path target = ... Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, target.resolve(source.relativize(file))); return CONTINUE; } });
Unchecked exception thrown when path string cannot be converted into a Path because the path string contains invalid characters, or the path string is invalid for other file system specific reasons.
Unchecked exception thrown when path string cannot be converted into a Path because the path string contains invalid characters, or the path string is invalid for other file system specific reasons.
The Permission class for link creation operations.
The following table provides a summary description of what the permission allows, and discusses the risks of granting code the permission.
Permission Target Name What the Permission Allows Risks of Allowing this Permission
hard Ability to add an existing file to a directory. This is sometimes known as creating a link, or hard link. Extreme care should be taken when granting this permission. It allows linking to any file or directory in the file system thus allowing the attacker access to all files.
symbolic Ability to create symbolic links. Extreme care should be taken when granting this permission. It allows linking to any file or directory in the file system thus allowing the attacker to access to all files.
The Permission class for link creation operations. The following table provides a summary description of what the permission allows, and discusses the risks of granting code the permission. Permission Target Name What the Permission Allows Risks of Allowing this Permission hard Ability to add an existing file to a directory. This is sometimes known as creating a link, or hard link. Extreme care should be taken when granting this permission. It allows linking to any file or directory in the file system thus allowing the attacker access to all files. symbolic Ability to create symbolic links. Extreme care should be taken when granting this permission. It allows linking to any file or directory in the file system thus allowing the attacker to access to all files.
Checked exception thrown when an attempt is made to access a file that does not exist.
Checked exception thrown when an attempt is made to access a file that does not exist.
Checked exception thrown when a file system operation, intended for a directory, fails because the file is not a directory.
Checked exception thrown when a file system operation, intended for a directory, fails because the file is not a directory.
Checked exception thrown when a file system operation fails because a file is not a symbolic link.
Checked exception thrown when a file system operation fails because a file is not a symbolic link.
An object that configures how to open or create a file.
Objects of this type are used by methods such as newOutputStream, newByteChannel, FileChannel.open, and AsynchronousFileChannel.open when opening or creating a file.
The StandardOpenOption enumeration type defines the standard options.
An object that configures how to open or create a file. Objects of this type are used by methods such as newOutputStream, newByteChannel, FileChannel.open, and AsynchronousFileChannel.open when opening or creating a file. The StandardOpenOption enumeration type defines the standard options.
No vars found in this namespace.
An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.
A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. The other name elements are directory names. A Path can represent a root, a root and a sequence of names, or simply one or more name elements. A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system. Path defines the getFileName, getParent, getRoot, and subpath methods to access the path components or a subsequence of its name elements.
In addition to accessing the components of a path, a Path also defines the resolve and resolveSibling methods to combine paths. The relativize method that can be used to construct a relative path between two paths. Paths can be compared, and tested against each other using the startsWith and endsWith methods.
This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.
WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases.
Accessing Files Paths may be used with the Files class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader to read text from a file "access.log". The file is located in a directory "logs" relative to the current working directory and is UTF-8 encoded.
Path path = FileSystems.getDefault().getPath("logs", "access.log");
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Interoperability Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path.
Concurrency Implementations of this interface are immutable and safe for use by multiple concurrent threads.
An object that may be used to locate a file in a file system. It will typically represent a system dependent file path. A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. The other name elements are directory names. A Path can represent a root, a root and a sequence of names, or simply one or more name elements. A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system. Path defines the getFileName, getParent, getRoot, and subpath methods to access the path components or a subsequence of its name elements. In addition to accessing the components of a path, a Path also defines the resolve and resolveSibling methods to combine paths. The relativize method that can be used to construct a relative path between two paths. Paths can be compared, and tested against each other using the startsWith and endsWith methods. This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched. WARNING: This interface is only intended to be implemented by those developing custom file system implementations. Methods may be added to this interface in future releases. Accessing Files Paths may be used with the Files class to operate on files, directories, and other types of files. For example, suppose we want a BufferedReader to read text from a file "access.log". The file is located in a directory "logs" relative to the current working directory and is UTF-8 encoded. Path path = FileSystems.getDefault().getPath("logs", "access.log"); BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); Interoperability Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path. Concurrency Implementations of this interface are immutable and safe for use by multiple concurrent threads.
An interface that is implemented by objects that perform match operations on paths.
An interface that is implemented by objects that perform match operations on paths.
This class consists exclusively of static methods that return a Path by converting a path string or URI.
This class consists exclusively of static methods that return a Path by converting a path string or URI.
Unchecked exception thrown when an attempt is made to invoke a method on an object created by one file system provider with a parameter created by a different file system provider.
Unchecked exception thrown when an attempt is made to invoke a method on an object created by one file system provider with a parameter created by a different file system provider.
Runtime exception thrown when a provider of the required type cannot be found.
Runtime exception thrown when a provider of the required type cannot be found.
Unchecked exception thrown when an attempt is made to update an object associated with a read-only FileSystem.
Unchecked exception thrown when an attempt is made to update an object associated with a read-only FileSystem.
A DirectoryStream that defines operations on files that are located relative to an open directory. A SecureDirectoryStream is intended for use by sophisticated or security sensitive applications requiring to traverse file trees or otherwise operate on directories in a race-free manner. Race conditions can arise when a sequence of file operations cannot be carried out in isolation. Each of the file operations defined by this interface specify a relative path. All access to the file is relative to the open directory irrespective of if the directory is moved or replaced by an attacker while the directory is open. A SecureDirectoryStream may also be used as a virtual working directory.
A SecureDirectoryStream requires corresponding support from the underlying operating system. Where an implementation supports this features then the DirectoryStream returned by the newDirectoryStream method will be a SecureDirectoryStream and must be cast to that type in order to invoke the methods defined by this interface.
In the case of the default provider, and a security manager is set, then the permission checks are performed using the path obtained by resolving the given relative path against the original path of the directory (irrespective of if the directory is moved since it was opened).
A DirectoryStream that defines operations on files that are located relative to an open directory. A SecureDirectoryStream is intended for use by sophisticated or security sensitive applications requiring to traverse file trees or otherwise operate on directories in a race-free manner. Race conditions can arise when a sequence of file operations cannot be carried out in isolation. Each of the file operations defined by this interface specify a relative path. All access to the file is relative to the open directory irrespective of if the directory is moved or replaced by an attacker while the directory is open. A SecureDirectoryStream may also be used as a virtual working directory. A SecureDirectoryStream requires corresponding support from the underlying operating system. Where an implementation supports this features then the DirectoryStream returned by the newDirectoryStream method will be a SecureDirectoryStream and must be cast to that type in order to invoke the methods defined by this interface. In the case of the default provider, and a security manager is set, then the permission checks are performed using the path obtained by resolving the given relative path against the original path of the directory (irrespective of if the directory is moved since it was opened).
A simple visitor of files with default behavior to visit all files and to re-throw I/O errors.
Methods in this class may be overridden subject to their general contract.
A simple visitor of files with default behavior to visit all files and to re-throw I/O errors. Methods in this class may be overridden subject to their general contract.
No vars found in this namespace.
Service-provider class for file systems. The methods defined by the Files class will typically delegate to an instance of this class.
A file system provider is a concrete implementation of this class that implements the abstract methods defined by this class. A provider is identified by a URI scheme. The default provider is identified by the URI scheme "file". It creates the FileSystem that provides access to the file systems accessible to the Java virtual machine. The FileSystems class defines how file system providers are located and loaded. The default provider is typically a system-default provider but may be overridden if the system property java.nio.file.spi.DefaultFileSystemProvider is set. In that case, the provider has a one argument constructor whose formal parameter type is FileSystemProvider. All other providers have a zero argument constructor that initializes the provider.
A provider is a factory for one or more FileSystem instances. Each file system is identified by a URI where the URI's scheme matches the provider's scheme. The default file system, for example, is identified by the URI "file:///". A memory-based file system, for example, may be identified by a URI such as "memory:///?name=logfs". The newFileSystem method may be used to create a file system, and the getFileSystem method may be used to obtain a reference to an existing file system created by the provider. Where a provider is the factory for a single file system then it is provider dependent if the file system is created when the provider is initialized, or later when the newFileSystem method is invoked. In the case of the default provider, the FileSystem is created when the provider is initialized.
All of the methods in this class are safe for use by multiple concurrent threads.
Service-provider class for file systems. The methods defined by the Files class will typically delegate to an instance of this class. A file system provider is a concrete implementation of this class that implements the abstract methods defined by this class. A provider is identified by a URI scheme. The default provider is identified by the URI scheme "file". It creates the FileSystem that provides access to the file systems accessible to the Java virtual machine. The FileSystems class defines how file system providers are located and loaded. The default provider is typically a system-default provider but may be overridden if the system property java.nio.file.spi.DefaultFileSystemProvider is set. In that case, the provider has a one argument constructor whose formal parameter type is FileSystemProvider. All other providers have a zero argument constructor that initializes the provider. A provider is a factory for one or more FileSystem instances. Each file system is identified by a URI where the URI's scheme matches the provider's scheme. The default file system, for example, is identified by the URI "file:///". A memory-based file system, for example, may be identified by a URI such as "memory:///?name=logfs". The newFileSystem method may be used to create a file system, and the getFileSystem method may be used to obtain a reference to an existing file system created by the provider. Where a provider is the factory for a single file system then it is provider dependent if the file system is created when the provider is initialized, or later when the newFileSystem method is invoked. In the case of the default provider, the FileSystem is created when the provider is initialized. All of the methods in this class are safe for use by multiple concurrent threads.
A file type detector for probing a file to guess its file type.
A file type detector is a concrete implementation of this class, has a zero-argument constructor, and implements the abstract methods specified below.
The means by which a file type detector determines the file type is highly implementation specific. A simple implementation might examine the file extension (a convention used in some platforms) and map it to a file type. In other cases, the file type may be stored as a file attribute or the bytes in a file may be examined to guess its file type.
A file type detector for probing a file to guess its file type. A file type detector is a concrete implementation of this class, has a zero-argument constructor, and implements the abstract methods specified below. The means by which a file type detector determines the file type is highly implementation specific. A simple implementation might examine the file extension (a convention used in some platforms) and map it to a file type. In other cases, the file type may be stored as a file attribute or the bytes in a file may be examined to guess its file type.
Defines the standard event kinds.
Defines the standard event kinds.
An object that may be registered with a watch service so that it can be watched for changes and events.
This interface defines the register method to register the object with a WatchService returning a WatchKey to represent the registration. An object may be registered with more than one watch service. Registration with a watch service is cancelled by invoking the key's cancel method.
An object that may be registered with a watch service so that it can be watched for changes and events. This interface defines the register method to register the object with a WatchService returning a WatchKey to represent the registration. An object may be registered with more than one watch service. Registration with a watch service is cancelled by invoking the key's cancel method.
An event or a repeated event for an object that is registered with a WatchService.
An event is classified by its kind and has a count to indicate the number of times that the event has been observed. This allows for efficient representation of repeated events. The context method returns any context associated with the event. In the case of a repeated event then the context is the same for all events.
Watch events are immutable and safe for use by multiple concurrent threads.
An event or a repeated event for an object that is registered with a WatchService. An event is classified by its kind and has a count to indicate the number of times that the event has been observed. This allows for efficient representation of repeated events. The context method returns any context associated with the event. In the case of a repeated event then the context is the same for all events. Watch events are immutable and safe for use by multiple concurrent threads.
An event kind, for the purposes of identification.
An event kind, for the purposes of identification.
An event modifier that qualifies how a Watchable is registered with a WatchService.
This release does not define any standard modifiers.
An event modifier that qualifies how a Watchable is registered with a WatchService. This release does not define any standard modifiers.
A token representing the registration of a watchable object with a WatchService.
A watch key is created when a watchable object is registered with a watch service. The key remains valid until:
It is cancelled, explicitly, by invoking its cancel method, or Cancelled implicitly, because the object is no longer accessible, or By closing the watch service.
A watch key has a state. When initially created the key is said to be ready. When an event is detected then the key is signalled and queued so that it can be retrieved by invoking the watch service's poll or take methods. Once signalled, a key remains in this state until its reset method is invoked to return the key to the ready state. Events detected while the key is in the signalled state are queued but do not cause the key to be re-queued for retrieval from the watch service. Events are retrieved by invoking the key's pollEvents method. This method retrieves and removes all events accumulated for the object. When initially created, a watch key has no pending events. Typically events are retrieved when the key is in the signalled state leading to the following idiom:
for (;;) {
// retrieve key
WatchKey key = watcher.take();
// process events
for (WatchEvent<?> event: key.pollEvents()) {
:
}
// reset the key
boolean valid = key.reset();
if (!valid) {
// object no longer registered
}
}
Watch keys are safe for use by multiple concurrent threads. Where there are several threads retrieving signalled keys from a watch service then care should be taken to ensure that the reset method is only invoked after the events for the object have been processed. This ensures that one thread is processing the events for an object at any time.
A token representing the registration of a watchable object with a WatchService. A watch key is created when a watchable object is registered with a watch service. The key remains valid until: It is cancelled, explicitly, by invoking its cancel method, or Cancelled implicitly, because the object is no longer accessible, or By closing the watch service. A watch key has a state. When initially created the key is said to be ready. When an event is detected then the key is signalled and queued so that it can be retrieved by invoking the watch service's poll or take methods. Once signalled, a key remains in this state until its reset method is invoked to return the key to the ready state. Events detected while the key is in the signalled state are queued but do not cause the key to be re-queued for retrieval from the watch service. Events are retrieved by invoking the key's pollEvents method. This method retrieves and removes all events accumulated for the object. When initially created, a watch key has no pending events. Typically events are retrieved when the key is in the signalled state leading to the following idiom: for (;;) { // retrieve key WatchKey key = watcher.take(); // process events for (WatchEvent<?> event: key.pollEvents()) { : } // reset the key boolean valid = key.reset(); if (!valid) { // object no longer registered } } Watch keys are safe for use by multiple concurrent threads. Where there are several threads retrieving signalled keys from a watch service then care should be taken to ensure that the reset method is only invoked after the events for the object have been processed. This ensures that one thread is processing the events for an object at any time.
A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
A Watchable object is registered with a watch service by invoking its register method, returning a WatchKey to represent the registration. When an event for an object is detected the key is signalled, and if not currently signalled, it is queued to the watch service so that it can be retrieved by consumers that invoke the poll or take methods to retrieve keys and process events. Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signalled and re-queued with further events.
Registration with a watch service is cancelled by invoking the key's cancel method. A key that is queued at the time that it is cancelled remains in the queue until it is retrieved. Depending on the object, a key may be cancelled automatically. For example, suppose a directory is watched and the watch service detects that it has been deleted or its file system is no longer accessible. When a key is cancelled in this manner it is signalled and queued, if not currently signalled. To ensure that the consumer is notified the return value from the reset method indicates if the key is valid.
A watch service is safe for use by multiple concurrent consumers. To ensure that only one consumer processes the events for a particular object at any time then care should be taken to ensure that the key's reset method is only invoked after its events have been processed. The close method may be invoked at any time to close the service causing any threads waiting to retrieve keys, to throw ClosedWatchServiceException.
File systems may report events faster than they can be retrieved or processed and an implementation may impose an unspecified limit on the number of events that it may accumulate. Where an implementation knowingly discards events then it arranges for the key's pollEvents method to return an element with an event type of OVERFLOW. This event can be used by the consumer as a trigger to re-examine the state of the object.
When an event is reported to indicate that a file in a watched directory has been modified then there is no guarantee that the program (or programs) that have modified the file have completed. Care should be taken to coordinate access with other programs that may be updating the file. The FileChannel class defines methods to lock regions of a file against access by other programs.
Platform dependencies
The implementation that observes events from the file system is intended to map directly on to the native file event notification facility where available, or to use a primitive mechanism, such as polling, when a native facility is not available. Consequently, many of the details on how events are detected, their timeliness, and whether their ordering is preserved are highly implementation specific. For example, when a file in a watched directory is modified then it may result in a single ENTRY_MODIFY event in some implementations but several events in other implementations. Short-lived files (meaning files that are deleted very quickly after they are created) may not be detected by primitive implementations that periodically poll the file system to detect changes.
If a watched file is not located on a local storage device then it is implementation specific if changes to the file can be detected. In particular, it is not required that changes to files carried out on remote systems be detected.
A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted. A Watchable object is registered with a watch service by invoking its register method, returning a WatchKey to represent the registration. When an event for an object is detected the key is signalled, and if not currently signalled, it is queued to the watch service so that it can be retrieved by consumers that invoke the poll or take methods to retrieve keys and process events. Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signalled and re-queued with further events. Registration with a watch service is cancelled by invoking the key's cancel method. A key that is queued at the time that it is cancelled remains in the queue until it is retrieved. Depending on the object, a key may be cancelled automatically. For example, suppose a directory is watched and the watch service detects that it has been deleted or its file system is no longer accessible. When a key is cancelled in this manner it is signalled and queued, if not currently signalled. To ensure that the consumer is notified the return value from the reset method indicates if the key is valid. A watch service is safe for use by multiple concurrent consumers. To ensure that only one consumer processes the events for a particular object at any time then care should be taken to ensure that the key's reset method is only invoked after its events have been processed. The close method may be invoked at any time to close the service causing any threads waiting to retrieve keys, to throw ClosedWatchServiceException. File systems may report events faster than they can be retrieved or processed and an implementation may impose an unspecified limit on the number of events that it may accumulate. Where an implementation knowingly discards events then it arranges for the key's pollEvents method to return an element with an event type of OVERFLOW. This event can be used by the consumer as a trigger to re-examine the state of the object. When an event is reported to indicate that a file in a watched directory has been modified then there is no guarantee that the program (or programs) that have modified the file have completed. Care should be taken to coordinate access with other programs that may be updating the file. The FileChannel class defines methods to lock regions of a file against access by other programs. Platform dependencies The implementation that observes events from the file system is intended to map directly on to the native file event notification facility where available, or to use a primitive mechanism, such as polling, when a native facility is not available. Consequently, many of the details on how events are detected, their timeliness, and whether their ordering is preserved are highly implementation specific. For example, when a file in a watched directory is modified then it may result in a single ENTRY_MODIFY event in some implementations but several events in other implementations. Short-lived files (meaning files that are deleted very quickly after they are created) may not be detected by primitive implementations that periodically poll the file system to detect changes. If a watched file is not located on a local storage device then it is implementation specific if changes to the file can be detected. In particular, it is not required that changes to files carried out on remote systems be detected.
A float buffer.
This class defines four categories of operations upon float buffers:
Absolute and relative get and put methods that read and write single floats;
Relative bulk get methods that transfer contiguous sequences of floats from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of floats from a float array or some other float buffer into this buffer; and
Methods for compacting, duplicating, and slicing a float buffer.
Float buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing float array into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, a float buffer is either direct or non-direct. A float buffer created via the wrap methods of this class will be non-direct. A float buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a float buffer is direct may be determined by invoking the isDirect method.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
A float buffer. This class defines four categories of operations upon float buffers: Absolute and relative get and put methods that read and write single floats; Relative bulk get methods that transfer contiguous sequences of floats from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of floats from a float array or some other float buffer into this buffer; and Methods for compacting, duplicating, and slicing a float buffer. Float buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing float array into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a float buffer is either direct or non-direct. A float buffer created via the wrap methods of this class will be non-direct. A float buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a float buffer is direct may be determined by invoking the isDirect method. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
An int buffer.
This class defines four categories of operations upon int buffers:
Absolute and relative get and put methods that read and write single ints;
Relative bulk get methods that transfer contiguous sequences of ints from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of ints from an int array or some other int buffer into this buffer; and
Methods for compacting, duplicating, and slicing an int buffer.
Int buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing int array into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, an int buffer is either direct or non-direct. A int buffer created via the wrap methods of this class will be non-direct. An int buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not an int buffer is direct may be determined by invoking the isDirect method.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
An int buffer. This class defines four categories of operations upon int buffers: Absolute and relative get and put methods that read and write single ints; Relative bulk get methods that transfer contiguous sequences of ints from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of ints from an int array or some other int buffer into this buffer; and Methods for compacting, duplicating, and slicing an int buffer. Int buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing int array into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, an int buffer is either direct or non-direct. A int buffer created via the wrap methods of this class will be non-direct. An int buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not an int buffer is direct may be determined by invoking the isDirect method. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
Unchecked exception thrown when an attempt is made to reset a buffer when its mark is not defined.
Unchecked exception thrown when an attempt is made to reset a buffer when its mark is not defined.
A long buffer.
This class defines four categories of operations upon long buffers:
Absolute and relative get and put methods that read and write single longs;
Relative bulk get methods that transfer contiguous sequences of longs from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of longs from a long array or some other long buffer into this buffer; and
Methods for compacting, duplicating, and slicing a long buffer.
Long buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing long array into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, a long buffer is either direct or non-direct. A long buffer created via the wrap methods of this class will be non-direct. A long buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a long buffer is direct may be determined by invoking the isDirect method.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
A long buffer. This class defines four categories of operations upon long buffers: Absolute and relative get and put methods that read and write single longs; Relative bulk get methods that transfer contiguous sequences of longs from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of longs from a long array or some other long buffer into this buffer; and Methods for compacting, duplicating, and slicing a long buffer. Long buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing long array into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a long buffer is either direct or non-direct. A long buffer created via the wrap methods of this class will be non-direct. A long buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a long buffer is direct may be determined by invoking the isDirect method. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
A direct byte buffer whose content is a memory-mapped region of a file.
Mapped byte buffers are created via the FileChannel.map method. This class extends the ByteBuffer class with operations that are specific to memory-mapped file regions.
A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected.
The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified.
All or part of a mapped byte buffer may become inaccessible at any time, for example if the mapped file is truncated. An attempt to access an inaccessible region of a mapped byte buffer will not change the buffer'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 program, or by a concurrently running program, except to read or write the file's content.
Mapped byte buffers otherwise behave no differently than ordinary direct byte buffers.
A direct byte buffer whose content is a memory-mapped region of a file. Mapped byte buffers are created via the FileChannel.map method. This class extends the ByteBuffer class with operations that are specific to memory-mapped file regions. A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected. The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified. All or part of a mapped byte buffer may become inaccessible at any time, for example if the mapped file is truncated. An attempt to access an inaccessible region of a mapped byte buffer will not change the buffer'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 program, or by a concurrently running program, except to read or write the file's content. Mapped byte buffers otherwise behave no differently than ordinary direct byte buffers.
Unchecked exception thrown when a content-mutation method such as put or compact is invoked upon a read-only buffer.
Unchecked exception thrown when a content-mutation method such as put or compact is invoked upon a read-only buffer.
A short buffer.
This class defines four categories of operations upon short buffers:
Absolute and relative get and put methods that read and write single shorts;
Relative bulk get methods that transfer contiguous sequences of shorts from this buffer into an array; and
Relative bulk put methods that transfer contiguous sequences of shorts from a short array or some other short buffer into this buffer; and
Methods for compacting, duplicating, and slicing a short buffer.
Short buffers can be created either by allocation, which allocates space for the buffer's
content, by wrapping an existing short array into a buffer, or by creating a view of an existing byte buffer.
Like a byte buffer, a short buffer is either direct or non-direct. A short buffer created via the wrap methods of this class will be non-direct. A short buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a short buffer is direct may be determined by invoking the isDirect method.
Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
A short buffer. This class defines four categories of operations upon short buffers: Absolute and relative get and put methods that read and write single shorts; Relative bulk get methods that transfer contiguous sequences of shorts from this buffer into an array; and Relative bulk put methods that transfer contiguous sequences of shorts from a short array or some other short buffer into this buffer; and Methods for compacting, duplicating, and slicing a short buffer. Short buffers can be created either by allocation, which allocates space for the buffer's content, by wrapping an existing short array into a buffer, or by creating a view of an existing byte buffer. Like a byte buffer, a short buffer is either direct or non-direct. A short buffer created via the wrap methods of this class will be non-direct. A short buffer created as a view of a byte buffer will be direct if, and only if, the byte buffer itself is direct. Whether or not a short buffer is direct may be determined by invoking the isDirect method. Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained.
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close