1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package java.nio.channels;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.MappedByteBuffer;
22 import java.nio.channels.spi.AbstractInterruptibleChannel;
25 * An abstract channel type for interaction with a platform file.
27 * A {@code FileChannel} defines the methods for reading, writing, memory
28 * mapping, and manipulating the logical state of a platform file. This type
29 * does not have a method for opening files, since this behavior has been
30 * delegated to the {@link java.io.FileInputStream},
31 * {@link java.io.FileOutputStream} and {@link java.io.RandomAccessFile} types.
33 * FileChannels created from a {@code FileInputStream} or a
34 * {@code RandomAccessFile} created in mode "r", are read-only. FileChannels
35 * created from a {@code FileOutputStream} are write-only. FileChannels created
36 * from a {@code RandomAccessFile} created in mode "rw" are read/write.
37 * FileChannels created from a {@code RandomAccessFile} that was opened in
38 * append-mode will also be in append-mode -- meaning that each write will be
39 * proceeded by a seek to the end of file.
41 * FileChannels have a virtual pointer into the file which is referred to as a
42 * file <em>position</em>. The position can be manipulated by moving it
43 * within the file, and the current position can be queried.
45 * FileChannels also have an associated <em>size</em>. The size of the file
46 * is the number of bytes that it currently contains. The size can be
47 * manipulated by adding more bytes to the end of the file (which increases the
48 * size) or truncating the file (which decreases the size). The current size can
51 * FileChannels have operations beyond the simple read, write, and close. They
54 * <li>request that cached data be forced onto the disk,</li>
55 * <li>lock ranges of bytes associated with the file,</li>
56 * <li>transfer data directly to another channel in a manner that has the
57 * potential to be optimized by the platform,</li>
58 * <li>memory-mapping files into NIO buffers to provide efficient manipulation
60 * <li>read and write to the file at absolute byte offsets in a fashion that
61 * does not modify the current position.</li>
64 * FileChannels are thread-safe. Only one operation involving manipulation of
65 * the file position may be executed at the same time. Subsequent calls to such
66 * operations will block, and one of those blocked will be freed to continue
67 * when the first operation has completed. There is no ordered queue or fairness
68 * applied to the blocked threads.
70 * It is undefined whether operations that do not manipulate the file position
71 * will also block when there are any other operations in-flight.
73 * The logical view of the underlying file is consistent across all FileChannels
74 * and I/O streams opened on the same file by the same virtual machine process.
75 * Therefore, modifications performed via a channel will be visible to the
76 * stream and vice versa; this includes modifications to the file position,
79 public abstract class FileChannel extends AbstractInterruptibleChannel
80 implements GatheringByteChannel, ScatteringByteChannel, ByteChannel {
83 * {@code MapMode} defines file mapping mode constants.
85 public static class MapMode {
87 * Private mapping mode (equivalent to copy on write).
89 public static final MapMode PRIVATE = new MapMode("PRIVATE");
92 * Read-only mapping mode.
94 public static final MapMode READ_ONLY = new MapMode("READ_ONLY");
97 * Read-write mapping mode.
99 public static final MapMode READ_WRITE = new MapMode("READ_WRITE");
101 // The string used to display the mapping mode.
102 private final String displayName;
105 * Private constructor prevents others creating new modes.
107 private MapMode(String displayName) {
109 this.displayName = displayName;
113 * Returns a string version of the mapping mode.
115 * @return this map mode as string.
118 public String toString() {
124 * Protected default constructor.
126 protected FileChannel() {
131 * Requests that all updates to this channel are committed to the storage
134 * When this method returns, all modifications made to the platform file
135 * underlying this channel have been committed if the file resides on a
136 * local storage device. If the file is not hosted locally, for example on a
137 * networked file system, then applications cannot be certain that the
138 * modifications have been committed.
140 * There are no assurances given that changes made to the file using methods
141 * defined elsewhere will be committed. For example, changes made via a
142 * mapped byte buffer may not be committed.
144 * The <code>metadata</code> parameter indicates whether the update should
145 * include the file's metadata such as last modification time, last access
146 * time, etc. Note that passing <code>true</code> may invoke an underlying
147 * write to the operating system (if the platform is maintaining metadata
148 * such as last access time), even if the channel is opened read-only.
151 * {@code true} if the file metadata should be flushed in
152 * addition to the file content, {@code false} otherwise.
153 * @throws ClosedChannelException
154 * if this channel is already closed.
155 * @throws IOException
156 * if another I/O error occurs.
158 public abstract void force(boolean metadata) throws IOException;
161 * Obtains an exclusive lock on this file.
163 * This is a convenience method for acquiring a maximum length lock on a
164 * file. It is equivalent to:
165 * {@code fileChannel.lock(0L, Long.MAX_VALUE, false);}
167 * @return the lock object representing the locked file area.
168 * @throws ClosedChannelException
169 * the file channel is closed.
170 * @throws NonWritableChannelException
171 * this channel was not opened for writing.
172 * @throws OverlappingFileLockException
173 * either a lock is already held that overlaps this lock
174 * request, or another thread is waiting to acquire a lock that
175 * will overlap with this request.
176 * @throws FileLockInterruptionException
177 * the calling thread was interrupted while waiting to acquire
179 * @throws AsynchronousCloseException
180 * the channel was closed while the calling thread was waiting
181 * to acquire the lock.
182 * @throws IOException
183 * if another I/O error occurs while obtaining the requested
186 public final FileLock lock() throws IOException {
187 return lock(0L, Long.MAX_VALUE, false);
191 * Obtains a lock on a specified region of the file.
193 * This is the blocking version of lock acquisition, see also the
194 * <code>tryLock()</code> methods.
196 * Attempts to acquire an overlapping lock region will fail. The attempt
197 * will fail if the overlapping lock has already been obtained, or if
198 * another thread is currently waiting to acquire the overlapping lock.
200 * If the request is not for an overlapping lock, the thread calling this
201 * method will block until the lock is obtained (likely by no contention or
202 * another process releasing a lock), or until this thread is interrupted or
203 * the channel is closed.
205 * If the lock is obtained successfully then the {@link FileLock} object
206 * returned represents the lock for subsequent operations on the locked
209 * If the thread is interrupted while waiting for the lock, the thread is
210 * set to the interrupted state and throws a
211 * {@link FileLockInterruptionException}. If this channel is closed while
212 * the thread is waiting to obtain the lock then the thread throws a
213 * {@link AsynchronousCloseException}.
215 * There is no requirement for the position and size to be within the
216 * current start and length of the file.
218 * Some platforms do not support shared locks, and if a request is made for
219 * a shared lock on such a platform, this method will attempt to acquire an
220 * exclusive lock instead. It is undefined whether the lock obtained is
221 * advisory or mandatory.
224 * the starting position for the locked region.
226 * the length of the locked region in bytes.
228 * a flag indicating whether an attempt should be made to acquire
230 * @return the file lock object.
231 * @throws IllegalArgumentException
232 * if {@code position} or {@code size} is negative.
233 * @throws ClosedChannelException
234 * if this channel is closed.
235 * @throws OverlappingFileLockException
236 * if the requested region overlaps an existing lock or pending
238 * @throws NonReadableChannelException
239 * if the channel is not opened in read-mode but shared is true.
240 * @throws NonWritableChannelException
241 * if the channel is not opened in write mode but shared is
243 * @throws AsynchronousCloseException
244 * if this channel is closed by another thread while this method
246 * @throws FileLockInterruptionException
247 * if the thread is interrupted while in the state of waiting on
248 * the desired file lock.
249 * @throws IOException
250 * if another I/O error occurs.
252 public abstract FileLock lock(long position, long size, boolean shared)
256 * Maps the file into memory. There can be three modes: read-only,
257 * read/write and private. After mapping, changes made to memory or the file
258 * channel do not affect the other storage place.
260 * Note: mapping a file into memory is usually expensive.
263 * one of the three mapping modes.
265 * the starting position of the file.
267 * the size of the region to map into memory.
268 * @return the mapped byte buffer.
269 * @throws NonReadableChannelException
270 * if the FileChannel is not opened for reading but the given
271 * mode is "READ_ONLY".
272 * @throws NonWritableChannelException
273 * if the FileChannel is not opened for writing but the given
274 * mode is not "READ_ONLY".
275 * @throws IllegalArgumentException
276 * if the given parameters of position and size are not correct.
277 * Both must be non negative. {@code size} also must not be
278 * bigger than max integer.
279 * @throws IOException
280 * if any I/O error occurs.
282 public abstract MappedByteBuffer map(FileChannel.MapMode mode,
283 long position, long size) throws IOException;
286 * Returns the current value of the file position pointer.
288 * @return the current position as a positive integer number of bytes from
289 * the start of the file.
290 * @throws ClosedChannelException
291 * if this channel is closed.
292 * @throws IOException
293 * if another I/O error occurs.
295 public abstract long position() throws IOException;
298 * Sets the file position pointer to a new value.
300 * The argument is the number of bytes counted from the start of the file.
301 * The position cannot be set to a value that is negative. The new position
302 * can be set beyond the current file size. If set beyond the current file
303 * size, attempts to read will return end of file. Write operations will
304 * succeed but they will fill the bytes between the current end of file and
305 * the new position with the required number of (unspecified) byte values.
308 * the new file position, in bytes.
309 * @return the receiver.
310 * @throws IllegalArgumentException
311 * if the new position is negative.
312 * @throws ClosedChannelException
313 * if this channel is closed.
314 * @throws IOException
315 * if another I/O error occurs.
317 public abstract FileChannel position(long offset) throws IOException;
320 * Reads bytes from this file channel into the given buffer.
322 * The maximum number of bytes that will be read is the remaining number of
323 * bytes in the buffer when the method is invoked. The bytes will be copied
324 * into the buffer starting at the buffer's current position.
326 * The call may block if other threads are also attempting to read from this
329 * Upon completion, the buffer's position is set to the end of the bytes
330 * that have been read. The buffer's limit is not changed.
333 * the byte buffer to receive the bytes.
334 * @return the number of bytes actually read.
335 * @throws AsynchronousCloseException
336 * if another thread closes the channel during the read.
337 * @throws ClosedByInterruptException
338 * if another thread interrupts the calling thread during the
340 * @throws ClosedChannelException
341 * if this channel is closed.
342 * @throws IOException
343 * if another I/O error occurs, details are in the message.
344 * @throws NonReadableChannelException
345 * if the channel has not been opened in a mode that permits
348 public abstract int read(ByteBuffer buffer) throws IOException;
351 * Reads bytes from this file channel into the given buffer starting from
352 * the specified file position.
354 * The bytes are read starting at the given file position (up to the
355 * remaining number of bytes in the buffer). The number of bytes actually
358 * If {@code position} is beyond the current end of file, then no bytes are
361 * Note that the file position is unmodified by this method.
364 * the buffer to receive the bytes.
366 * the (non-negative) position at which to read the bytes.
367 * @return the number of bytes actually read.
368 * @throws AsynchronousCloseException
369 * if this channel is closed by another thread while this method
371 * @throws ClosedByInterruptException
372 * if another thread interrupts the calling thread while this
373 * operation is in progress. The calling thread will have the
374 * interrupt state set, and the channel will be closed.
375 * @throws ClosedChannelException
376 * if this channel is closed.
377 * @throws IllegalArgumentException
378 * if <code>position</code> is less than 0.
379 * @throws IOException
380 * if another I/O error occurs.
381 * @throws NonReadableChannelException
382 * if the channel has not been opened in a mode that permits
385 public abstract int read(ByteBuffer buffer, long position)
389 * Reads bytes from this file channel and stores them in the specified array
390 * of buffers. This method attempts to read as many bytes as can be stored
391 * in the buffer array from this channel and returns the number of bytes
392 * actually read. It also increases the file position by the number of bytes
395 * If a read operation is in progress, subsequent threads will block until
396 * the read is completed and will then contend for the ability to read.
398 * Calling this method is equivalent to calling
399 * {@code read(buffers, 0, buffers.length);}
402 * the array of byte buffers into which the bytes will be copied.
403 * @return the number of bytes actually read.
404 * @throws AsynchronousCloseException
405 * if this channel is closed by another thread during this read
407 * @throws ClosedByInterruptException
408 * if the thread is interrupted by another thread during this
410 * @throws ClosedChannelException
411 * if this channel is closed.
412 * @throws IOException
413 * if another I/O error occurs; details are in the message.
414 * @throws NonReadableChannelException
415 * if the channel has not been opened in a mode that permits
418 public final long read(ByteBuffer[] buffers) throws IOException {
419 return read(buffers, 0, buffers.length);
423 * Reads bytes from this file channel into a subset of the given buffers.
424 * This method attempts to read all {@code remaining()} bytes from {@code
425 * length} byte buffers, in order, starting at {@code targets[offset]}. It
426 * increases the file position by the number of bytes actually read. The
427 * number of bytes actually read is returned.
429 * If a read operation is in progress, subsequent threads will block until
430 * the read is completed and will then contend for the ability to read.
433 * the array of byte buffers into which the bytes will be copied.
435 * the index of the first buffer to store bytes in.
437 * the maximum number of buffers to store bytes in.
438 * @return the number of bytes actually read.
439 * @throws AsynchronousCloseException
440 * if this channel is closed by another thread during this read
442 * @throws ClosedByInterruptException
443 * if the thread is interrupted by another thread during this
445 * @throws ClosedChannelException
446 * if this channel is closed.
447 * @throws IndexOutOfBoundsException
448 * if {@code start < 0} or {@code number < 0}, or if
449 * {@code start + number} is greater than the size of
451 * @throws IOException
452 * if another I/O error occurs; details are in the message.
453 * @throws NonReadableChannelException
454 * if the channel has not been opened in a mode that permits
457 public abstract long read(ByteBuffer[] buffers, int start, int number)
461 * Returns the size of the file underlying this channel in bytes.
463 * @return the size of the file in bytes.
464 * @throws ClosedChannelException
465 * if this channel is closed.
466 * @throws IOException
467 * if an I/O error occurs while getting the size of the file.
469 public abstract long size() throws IOException;
472 * Reads up to {@code count} bytes from {@code src} and stores them in this
473 * channel's file starting at {@code position}. No bytes are transferred if
474 * {@code position} is larger than the size of this channel's file. Less
475 * than {@code count} bytes are transferred if there are less bytes
476 * remaining in the source channel or if the source channel is non-blocking
477 * and has less than {@code count} bytes immediately available in its output
480 * Note that this channel's position is not modified.
483 * the source channel to read bytes from.
485 * the non-negative start position.
487 * the non-negative number of bytes to transfer.
488 * @return the number of bytes that are transferred.
489 * @throws IllegalArgumentException
490 * if the parameters are invalid.
491 * @throws NonReadableChannelException
492 * if the source channel is not readable.
493 * @throws NonWritableChannelException
494 * if this channel is not writable.
495 * @throws ClosedChannelException
496 * if either channel has already been closed.
497 * @throws AsynchronousCloseException
498 * if either channel is closed by other threads during this
500 * @throws ClosedByInterruptException
501 * if the thread is interrupted during this operation.
502 * @throws IOException
503 * if any I/O error occurs.
505 public abstract long transferFrom(ReadableByteChannel src, long position,
506 long count) throws IOException;
509 * Reads up to {@code count} bytes from this channel's file starting at
510 * {@code position} and writes them to {@code target}. No bytes are
511 * transferred if {@code position} is larger than the size of this channel's
512 * file. Less than {@code count} bytes are transferred if there less bytes
513 * available from this channel's file or if the target channel is
514 * non-blocking and has less than {@code count} bytes free in its input
517 * Note that this channel's position is not modified.
520 * the non-negative position to begin.
522 * the non-negative number of bytes to transfer.
524 * the target channel to write to.
525 * @return the number of bytes that were transferred.
526 * @throws IllegalArgumentException
527 * if the parameters are invalid.
528 * @throws NonReadableChannelException
529 * if this channel is not readable.
530 * @throws NonWritableChannelException
531 * if the target channel is not writable.
532 * @throws ClosedChannelException
533 * if either channel has already been closed.
534 * @throws AsynchronousCloseException
535 * if either channel is closed by other threads during this
537 * @throws ClosedByInterruptException
538 * if the thread is interrupted during this operation.
539 * @throws IOException
540 * if any I/O error occurs.
542 public abstract long transferTo(long position, long count,
543 WritableByteChannel target) throws IOException;
546 * Truncates the file underlying this channel to a given size. Any bytes
547 * beyond the given size are removed from the file. If there are no bytes
548 * beyond the given size then the file contents are unmodified.
550 * If the file position is currently greater than the given size, then it is
551 * set to the new size.
554 * the maximum size of the underlying file.
555 * @throws IllegalArgumentException
556 * if the requested size is negative.
557 * @throws ClosedChannelException
558 * if this channel is closed.
559 * @throws NonWritableChannelException
560 * if the channel cannot be written to.
561 * @throws IOException
562 * if another I/O error occurs.
563 * @return this channel.
565 public abstract FileChannel truncate(long size) throws IOException;
568 * Attempts to acquire an exclusive lock on this file without blocking.
570 * This is a convenience method for attempting to acquire a maximum length
571 * lock on the file. It is equivalent to:
572 * {@code fileChannel.tryLock(0L, Long.MAX_VALUE, false);}
574 * The method returns {@code null} if the acquisition would result in an
575 * overlapped lock with another OS process.
577 * @return the file lock object, or {@code null} if the lock would overlap
578 * with an existing exclusive lock in another OS process.
579 * @throws ClosedChannelException
580 * if the file channel is closed.
581 * @throws OverlappingFileLockException
582 * if a lock already exists that overlaps this lock request or
583 * another thread is waiting to acquire a lock that will overlap
585 * @throws IOException
586 * if any I/O error occurs.
588 public final FileLock tryLock() throws IOException {
589 return tryLock(0L, Long.MAX_VALUE, false);
593 * Attempts to acquire an exclusive lock on this file without blocking. The
594 * method returns {@code null} if the acquisition would result in an
595 * overlapped lock with another OS process.
597 * It is possible to acquire a lock for any region even if it's completely
598 * outside of the file's size. The size of the lock is fixed. If the file
599 * grows outside of the lock that region of the file won't be locked by this
603 * the starting position.
605 * the size of file to lock.
607 * true if the lock is shared.
608 * @return the file lock object, or {@code null} if the lock would overlap
609 * with an existing exclusive lock in another OS process.
610 * @throws IllegalArgumentException
611 * if any parameters are invalid.
612 * @throws ClosedChannelException
613 * if the file channel is closed.
614 * @throws OverlappingFileLockException
615 * if a lock is already held that overlaps this lock request or
616 * another thread is waiting to acquire a lock that will overlap
618 * @throws IOException
619 * if any I/O error occurs.
621 public abstract FileLock tryLock(long position, long size, boolean shared)
625 * Writes bytes from the given byte buffer to this file channel.
627 * The bytes are written starting at the current file position, and after
628 * some number of bytes are written (up to the remaining number of bytes in
629 * the buffer) the file position is increased by the number of bytes
633 * the byte buffer containing the bytes to be written.
634 * @return the number of bytes actually written.
635 * @throws NonWritableChannelException
636 * if the channel was not opened for writing.
637 * @throws ClosedChannelException
638 * if the channel was already closed.
639 * @throws AsynchronousCloseException
640 * if another thread closes the channel during the write.
641 * @throws ClosedByInterruptException
642 * if another thread interrupts the calling thread while this
643 * operation is in progress. The interrupt state of the calling
644 * thread is set and the channel is closed.
645 * @throws IOException
646 * if another I/O error occurs, details are in the message.
647 * @see java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)
649 public abstract int write(ByteBuffer src) throws IOException;
652 * Writes bytes from the given buffer to this file channel starting at the
653 * given file position.
655 * The bytes are written starting at the given file position (up to the
656 * remaining number of bytes in the buffer). The number of bytes actually
657 * written is returned.
659 * If the position is beyond the current end of file, then the file is first
660 * extended up to the given position by the required number of unspecified
663 * Note that the file position is not modified by this method.
666 * the buffer containing the bytes to be written.
668 * the (non-negative) position at which to write the bytes.
669 * @return the number of bytes actually written.
670 * @throws IllegalArgumentException
671 * if <code>position</code> is less than 0.
672 * @throws ClosedChannelException
673 * if this channel is closed.
674 * @throws NonWritableChannelException
675 * if the channel was not opened in write-mode.
676 * @throws AsynchronousCloseException
677 * if this channel is closed by another thread while this method
679 * @throws ClosedByInterruptException
680 * if another thread interrupts the calling thread while this
681 * operation is in progress. The interrupt state of the calling
682 * thread is set and the channel is closed.
683 * @throws IOException
684 * if another I/O error occurs.
686 public abstract int write(ByteBuffer buffer, long position)
690 * Writes bytes from all the given byte buffers to this file channel.
692 * The bytes are written starting at the current file position, and after
693 * the bytes are written (up to the remaining number of bytes in all the
694 * buffers), the file position is increased by the number of bytes actually
697 * Calling this method is equivalent to calling
698 * {@code write(buffers, 0, buffers.length);}
701 * the buffers containing bytes to write.
702 * @return the number of bytes actually written.
703 * @throws AsynchronousCloseException
704 * if this channel is closed by another thread during this write
706 * @throws ClosedByInterruptException
707 * if another thread interrupts the calling thread while this
708 * operation is in progress. The interrupt state of the calling
709 * thread is set and the channel is closed.
710 * @throws ClosedChannelException
711 * if this channel is closed.
712 * @throws IOException
713 * if another I/O error occurs; details are in the message.
714 * @throws NonWritableChannelException
715 * if this channel was not opened for writing.
717 public final long write(ByteBuffer[] buffers) throws IOException {
718 return write(buffers, 0, buffers.length);
722 * Attempts to write a subset of the given bytes from the buffers to this
723 * file channel. This method attempts to write all {@code remaining()}
724 * bytes from {@code length} byte buffers, in order, starting at {@code
725 * sources[offset]}. The number of bytes actually written is returned.
727 * If a write operation is in progress, subsequent threads will block until
728 * the write is completed and then contend for the ability to write.
731 * the array of byte buffers that is the source for bytes written
734 * the index of the first buffer in {@code buffers }to get bytes
737 * the number of buffers to get bytes from.
738 * @return the number of bytes actually written to this channel.
739 * @throws AsynchronousCloseException
740 * if this channel is closed by another thread during this write
742 * @throws ClosedByInterruptException
743 * if another thread interrupts the calling thread while this
744 * operation is in progress. The interrupt state of the calling
745 * thread is set and the channel is closed.
746 * @throws ClosedChannelException
747 * if this channel is closed.
748 * @throws IndexOutOfBoundsException
749 * if {@code offset < 0} or {@code length < 0}, or if
750 * {@code offset + length} is greater than the size of
752 * @throws IOException
753 * if another I/O error occurs; details are in the message.
754 * @throws NonWritableChannelException
755 * if this channel was not opened for writing.
757 public abstract long write(ByteBuffer[] buffers, int offset, int length)