1 /*
   2  * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.channels;
  27 
  28 import java.io.*;
  29 import java.nio.ByteBuffer;
  30 import java.nio.MappedByteBuffer;
  31 import java.nio.channels.spi.AbstractInterruptibleChannel;
  32 import java.nio.file.*;
  33 import java.nio.file.attribute.FileAttribute;
  34 import java.nio.file.spi.*;
  35 import java.util.Objects;
  36 import java.util.Set;
  37 import java.util.HashSet;
  38 import java.util.Collections;
  39 
  40 /**
  41  * A channel for reading, writing, mapping, and manipulating a file.
  42  *
  43  * <p> A file channel is a {@link SeekableByteChannel} that is connected to
  44  * a file. It has a current <i>position</i> within its file which can
  45  * be both {@link #position() <i>queried</i>} and {@link #position(long)
  46  * <i>modified</i>}.  The file itself contains a variable-length sequence
  47  * of bytes that can be read and written and whose current {@link #size
  48  * <i>size</i>} can be queried.  The size of the file increases
  49  * when bytes are written beyond its current size; the size of the file
  50  * decreases when it is {@link #truncate <i>truncated</i>}.  The
  51  * file may also have some associated <i>metadata</i> such as access
  52  * permissions, content type, and last-modification time; this class does not
  53  * define methods for metadata access.
  54  *
  55  * <p> In addition to the familiar read, write, and close operations of byte
  56  * channels, this class defines the following file-specific operations: </p>
  57  *
  58  * <ul>
  59  *
  60  *   <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or
  61  *   {@link #write(ByteBuffer, long) <i>written</i>} at an absolute
  62  *   position in a file in a way that does not affect the channel's current
  63  *   position.  </p></li>
  64  *
  65  *   <li><p> A region of a file may be {@link #map <i>mapped</i>}
  66  *   directly into memory; for large files this is often much more efficient
  67  *   than invoking the usual {@code read} or {@code write} methods.
  68  *   </p></li>
  69  *
  70  *   <li><p> Updates made to a file may be {@link #force <i>forced
  71  *   out</i>} to the underlying storage device, ensuring that data are not
  72  *   lost in the event of a system crash.  </p></li>
  73  *
  74  *   <li><p> Bytes can be transferred from a file {@link #transferTo <i>to
  75  *   some other channel</i>}, and {@link #transferFrom <i>vice
  76  *   versa</i>}, in a way that can be optimized by many operating systems
  77  *   into a very fast transfer directly to or from the filesystem cache.
  78  *   </p></li>
  79  *
  80  *   <li><p> A region of a file may be {@link FileLock <i>locked</i>}
  81  *   against access by other programs.  </p></li>
  82  *
  83  * </ul>
  84  *
  85  * <p> File channels are safe for use by multiple concurrent threads.  The
  86  * {@link Channel#close close} method may be invoked at any time, as specified
  87  * by the {@link Channel} interface.  Only one operation that involves the
  88  * channel's position or can change its file's size may be in progress at any
  89  * given time; attempts to initiate a second such operation while the first is
  90  * still in progress will block until the first operation completes.  Other
  91  * operations, in particular those that take an explicit position, may proceed
  92  * concurrently; whether they in fact do so is dependent upon the underlying
  93  * implementation and is therefore unspecified.
  94  *
  95  * <p> The view of a file provided by an instance of this class is guaranteed
  96  * to be consistent with other views of the same file provided by other
  97  * instances in the same program.  The view provided by an instance of this
  98  * class may or may not, however, be consistent with the views seen by other
  99  * concurrently-running programs due to caching performed by the underlying
 100  * operating system and delays induced by network-filesystem protocols.  This
 101  * is true regardless of the language in which these other programs are
 102  * written, and whether they are running on the same machine or on some other
 103  * machine.  The exact nature of any such inconsistencies are system-dependent
 104  * and are therefore unspecified.
 105  *
 106  * <p> A file channel is created by invoking one of the {@link #open open}
 107  * methods defined by this class. A file channel can also be obtained from an
 108  * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link
 109  * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link
 110  * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking
 111  * that object's {@code getChannel} method, which returns a file channel that
 112  * is connected to the same underlying file. Where the file channel is obtained
 113  * from an existing stream or random access file then the state of the file
 114  * channel is intimately connected to that of the object whose {@code getChannel}
 115  * method returned the channel.  Changing the channel's position, whether
 116  * explicitly or by reading or writing bytes, will change the file position of
 117  * the originating object, and vice versa. Changing the file's length via the
 118  * file channel will change the length seen via the originating object, and vice
 119  * versa.  Changing the file's content by writing bytes will change the content
 120  * seen by the originating object, and vice versa.
 121  *
 122  * <a id="open-mode"></a> <p> At various points this class specifies that an
 123  * instance that is "open for reading," "open for writing," or "open for
 124  * reading and writing" is required.  A channel obtained via the {@link
 125  * java.io.FileInputStream#getChannel getChannel} method of a {@link
 126  * java.io.FileInputStream} instance will be open for reading.  A channel
 127  * obtained via the {@link java.io.FileOutputStream#getChannel getChannel}
 128  * method of a {@link java.io.FileOutputStream} instance will be open for
 129  * writing.  Finally, a channel obtained via the {@link
 130  * java.io.RandomAccessFile#getChannel getChannel} method of a {@link
 131  * java.io.RandomAccessFile} instance will be open for reading if the instance
 132  * was created with mode {@code "r"} and will be open for reading and writing
 133  * if the instance was created with mode {@code "rw"}.
 134  *
 135  * <a id="append-mode"></a><p> A file channel that is open for writing may be in
 136  * <i>append mode</i>, for example if it was obtained from a file-output stream
 137  * that was created by invoking the {@link
 138  * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean)
 139  * FileOutputStream(File,boolean)} constructor and passing {@code true} for
 140  * the second parameter.  In this mode each invocation of a relative write
 141  * operation first advances the position to the end of the file and then writes
 142  * the requested data.  Whether the advancement of the position and the writing
 143  * of the data are done in a single atomic operation is system-dependent and
 144  * therefore unspecified.
 145  *
 146  * @see java.io.FileInputStream#getChannel()
 147  * @see java.io.FileOutputStream#getChannel()
 148  * @see java.io.RandomAccessFile#getChannel()
 149  *
 150  * @author Mark Reinhold
 151  * @author Mike McCloskey
 152  * @author JSR-51 Expert Group
 153  * @since 1.4
 154  */
 155 
 156 public abstract class FileChannel
 157     extends AbstractInterruptibleChannel
 158     implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel
 159 {
 160     /**
 161      * Initializes a new instance of this class.
 162      */
 163     protected FileChannel() { }
 164 
 165     /**
 166      * Opens or creates a file, returning a file channel to access the file.
 167      *
 168      * <p> The {@code options} parameter determines how the file is opened.
 169      * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE
 170      * WRITE} options determine if the file should be opened for reading and/or
 171      * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND}
 172      * option) is contained in the array then the file is opened for reading.
 173      * By default reading or writing commences at the beginning of the file.
 174      *
 175      * <p> In the addition to {@code READ} and {@code WRITE}, the following
 176      * options may be present:
 177      *
 178      * <table class="striped">
 179      * <caption style="display:none">additional options</caption>
 180      * <thead>
 181      * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>
 182      * </thead>
 183      * <tbody>
 184      * <tr>
 185      *   <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th>
 186      *   <td> If this option is present then the file is opened for writing and
 187      *     each invocation of the channel's {@code write} method first advances
 188      *     the position to the end of the file and then writes the requested
 189      *     data. Whether the advancement of the position and the writing of the
 190      *     data are done in a single atomic operation is system-dependent and
 191      *     therefore unspecified. This option may not be used in conjunction
 192      *     with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>
 193      * </tr>
 194      * <tr>
 195      *   <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th>
 196      *   <td> If this option is present then the existing file is truncated to
 197      *   a size of 0 bytes. This option is ignored when the file is opened only
 198      *   for reading. </td>
 199      * </tr>
 200      * <tr>
 201      *   <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th>
 202      *   <td> If this option is present then a new file is created, failing if
 203      *   the file already exists. When creating a file the check for the
 204      *   existence of the file and the creation of the file if it does not exist
 205      *   is atomic with respect to other file system operations. This option is
 206      *   ignored when the file is opened only for reading. </td>
 207      * </tr>
 208      * <tr>
 209      *   <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th>
 210      *   <td> If this option is present then an existing file is opened if it
 211      *   exists, otherwise a new file is created. When creating a file the check
 212      *   for the existence of the file and the creation of the file if it does
 213      *   not exist is atomic with respect to other file system operations. This
 214      *   option is ignored if the {@code CREATE_NEW} option is also present or
 215      *   the file is opened only for reading. </td>
 216      * </tr>
 217      * <tr>
 218      *   <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th>
 219      *   <td> When this option is present then the implementation makes a
 220      *   <em>best effort</em> attempt to delete the file when closed by
 221      *   the {@link #close close} method. If the {@code close} method is not
 222      *   invoked then a <em>best effort</em> attempt is made to delete the file
 223      *   when the Java virtual machine terminates. </td>
 224      * </tr>
 225      * <tr>
 226      *   <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th>
 227      *   <td> When creating a new file this option is a <em>hint</em> that the
 228      *   new file will be sparse. This option is ignored when not creating
 229      *   a new file. </td>
 230      * </tr>
 231      * <tr>
 232      *   <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th>
 233      *   <td> Requires that every update to the file's content or metadata be
 234      *   written synchronously to the underlying storage device. (see <a
 235      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 236      *   integrity</a>). </td>
 237      * </tr>
 238      * <tr>
 239      *   <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th>
 240      *   <td> Requires that every update to the file's content be written
 241      *   synchronously to the underlying storage device. (see <a
 242      *   href="../file/package-summary.html#integrity"> Synchronized I/O file
 243      *   integrity</a>). </td>
 244      * </tr>
 245      * </tbody>
 246      * </table>
 247      *
 248      * <p> An implementation may also support additional options.
 249      *
 250      * <p> The {@code attrs} parameter is an optional array of file {@link
 251      * FileAttribute file-attributes} to set atomically when creating the file.
 252      *
 253      * <p> The new channel is created by invoking the {@link
 254      * FileSystemProvider#newFileChannel newFileChannel} method on the
 255      * provider that created the {@code Path}.
 256      *
 257      * @param   path
 258      *          The path of the file to open or create
 259      * @param   options
 260      *          Options specifying how the file is opened
 261      * @param   attrs
 262      *          An optional list of file attributes to set atomically when
 263      *          creating the file
 264      *
 265      * @return  A new file channel
 266      *
 267      * @throws  IllegalArgumentException
 268      *          If the set contains an invalid combination of options
 269      * @throws  UnsupportedOperationException
 270      *          If the {@code path} is associated with a provider that does not
 271      *          support creating file channels, or an unsupported open option is
 272      *          specified, or the array contains an attribute that cannot be set
 273      *          atomically when creating the file
 274      * @throws  IOException
 275      *          If an I/O error occurs
 276      * @throws  SecurityException
 277      *          If a security manager is installed and it denies an
 278      *          unspecified permission required by the implementation.
 279      *          In the case of the default provider, the {@link
 280      *          SecurityManager#checkRead(String)} method is invoked to check
 281      *          read access if the file is opened for reading. The {@link
 282      *          SecurityManager#checkWrite(String)} method is invoked to check
 283      *          write access if the file is opened for writing
 284      *
 285      * @since   1.7
 286      */
 287     public static FileChannel open(Path path,
 288                                    Set<? extends OpenOption> options,
 289                                    FileAttribute<?>... attrs)
 290         throws IOException
 291     {
 292         FileSystemProvider provider = path.getFileSystem().provider();
 293         return provider.newFileChannel(path, options, attrs);
 294     }
 295 
 296     @SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction
 297     private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];
 298 
 299     /**
 300      * Opens or creates a file, returning a file channel to access the file.
 301      *
 302      * <p> An invocation of this method behaves in exactly the same way as the
 303      * invocation
 304      * <pre>
 305      *     fc.{@link #open(Path,Set,FileAttribute[]) open}(file, opts, new FileAttribute&lt;?&gt;[0]);
 306      * </pre>
 307      * where {@code opts} is a set of the options specified in the {@code
 308      * options} array.
 309      *
 310      * @param   path
 311      *          The path of the file to open or create
 312      * @param   options
 313      *          Options specifying how the file is opened
 314      *
 315      * @return  A new file channel
 316      *
 317      * @throws  IllegalArgumentException
 318      *          If the set contains an invalid combination of options
 319      * @throws  UnsupportedOperationException
 320      *          If the {@code path} is associated with a provider that does not
 321      *          support creating file channels, or an unsupported open option is
 322      *          specified
 323      * @throws  IOException
 324      *          If an I/O error occurs
 325      * @throws  SecurityException
 326      *          If a security manager is installed and it denies an
 327      *          unspecified permission required by the implementation.
 328      *          In the case of the default provider, the {@link
 329      *          SecurityManager#checkRead(String)} method is invoked to check
 330      *          read access if the file is opened for reading. The {@link
 331      *          SecurityManager#checkWrite(String)} method is invoked to check
 332      *          write access if the file is opened for writing
 333      *
 334      * @since   1.7
 335      */
 336     public static FileChannel open(Path path, OpenOption... options)
 337         throws IOException
 338     {
 339         Set<OpenOption> set;
 340         if (options.length == 0) {
 341             set = Collections.emptySet();
 342         } else {
 343             set = new HashSet<>();
 344             Collections.addAll(set, options);
 345         }
 346         return open(path, set, NO_ATTRIBUTES);
 347     }
 348 
 349     // -- Channel operations --
 350 
 351     /**
 352      * Reads a sequence of bytes from this channel into the given buffer.
 353      *
 354      * <p> Bytes are read starting at this channel's current file position, and
 355      * then the file position is updated with the number of bytes actually
 356      * read.  Otherwise this method behaves exactly as specified in the {@link
 357      * ReadableByteChannel} interface. </p>
 358      */
 359     public abstract int read(ByteBuffer dst) throws IOException;
 360 
 361     /**
 362      * Reads a sequence of bytes from this channel into a subsequence of the
 363      * given buffers.
 364      *
 365      * <p> Bytes are read starting at this channel's current file position, and
 366      * then the file position is updated with the number of bytes actually
 367      * read.  Otherwise this method behaves exactly as specified in the {@link
 368      * ScatteringByteChannel} interface.  </p>
 369      */
 370     public abstract long read(ByteBuffer[] dsts, int offset, int length)
 371         throws IOException;
 372 
 373     /**
 374      * Reads a sequence of bytes from this channel into the given buffers.
 375      *
 376      * <p> Bytes are read starting at this channel's current file position, and
 377      * then the file position is updated with the number of bytes actually
 378      * read.  Otherwise this method behaves exactly as specified in the {@link
 379      * ScatteringByteChannel} interface.  </p>
 380      */
 381     public final long read(ByteBuffer[] dsts) throws IOException {
 382         return read(dsts, 0, dsts.length);
 383     }
 384 
 385     /**
 386      * Writes a sequence of bytes to this channel from the given buffer.
 387      *
 388      * <p> Bytes are written starting at this channel's current file position
 389      * unless the channel is in append mode, in which case the position is
 390      * first advanced to the end of the file.  The file is grown, if necessary,
 391      * to accommodate the written bytes, and then the file position is updated
 392      * with the number of bytes actually written.  Otherwise this method
 393      * behaves exactly as specified by the {@link WritableByteChannel}
 394      * interface. </p>
 395      */
 396     public abstract int write(ByteBuffer src) throws IOException;
 397 
 398     /**
 399      * Writes a sequence of bytes to this channel from a subsequence of the
 400      * given buffers.
 401      *
 402      * <p> Bytes are written starting at this channel's current file position
 403      * unless the channel is in append mode, in which case the position is
 404      * first advanced to the end of the file.  The file is grown, if necessary,
 405      * to accommodate the written bytes, and then the file position is updated
 406      * with the number of bytes actually written.  Otherwise this method
 407      * behaves exactly as specified in the {@link GatheringByteChannel}
 408      * interface.  </p>
 409      */
 410     public abstract long write(ByteBuffer[] srcs, int offset, int length)
 411         throws IOException;
 412 
 413     /**
 414      * Writes a sequence of bytes to this channel from the given buffers.
 415      *
 416      * <p> Bytes are written starting at this channel's current file position
 417      * unless the channel is in append mode, in which case the position is
 418      * first advanced to the end of the file.  The file is grown, if necessary,
 419      * to accommodate the written bytes, and then the file position is updated
 420      * with the number of bytes actually written.  Otherwise this method
 421      * behaves exactly as specified in the {@link GatheringByteChannel}
 422      * interface.  </p>
 423      */
 424     public final long write(ByteBuffer[] srcs) throws IOException {
 425         return write(srcs, 0, srcs.length);
 426     }
 427 
 428 
 429     // -- Other operations --
 430 
 431     /**
 432      * Returns this channel's file position.
 433      *
 434      * @return  This channel's file position,
 435      *          a non-negative integer counting the number of bytes
 436      *          from the beginning of the file to the current position
 437      *
 438      * @throws  ClosedChannelException
 439      *          If this channel is closed
 440      *
 441      * @throws  IOException
 442      *          If some other I/O error occurs
 443      */
 444     public abstract long position() throws IOException;
 445 
 446     /**
 447      * Sets this channel's file position.
 448      *
 449      * <p> Setting the position to a value that is greater than the file's
 450      * current size is legal but does not change the size of the file.  A later
 451      * attempt to read bytes at such a position will immediately return an
 452      * end-of-file indication.  A later attempt to write bytes at such a
 453      * position will cause the file to be grown to accommodate the new bytes;
 454      * the values of any bytes between the previous end-of-file and the
 455      * newly-written bytes are unspecified.  </p>
 456      *
 457      * @param  newPosition
 458      *         The new position, a non-negative integer counting
 459      *         the number of bytes from the beginning of the file
 460      *
 461      * @return  This file channel
 462      *
 463      * @throws  ClosedChannelException
 464      *          If this channel is closed
 465      *
 466      * @throws  IllegalArgumentException
 467      *          If the new position is negative
 468      *
 469      * @throws  IOException
 470      *          If some other I/O error occurs
 471      */
 472     public abstract FileChannel position(long newPosition) throws IOException;
 473 
 474     /**
 475      * Returns the current size of this channel's file.
 476      *
 477      * @return  The current size of this channel's file,
 478      *          measured in bytes
 479      *
 480      * @throws  ClosedChannelException
 481      *          If this channel is closed
 482      *
 483      * @throws  IOException
 484      *          If some other I/O error occurs
 485      */
 486     public abstract long size() throws IOException;
 487 
 488     /**
 489      * Truncates this channel's file to the given size.
 490      *
 491      * <p> If the given size is less than the file's current size then the file
 492      * is truncated, discarding any bytes beyond the new end of the file.  If
 493      * the given size is greater than or equal to the file's current size then
 494      * the file is not modified.  In either case, if this channel's file
 495      * position is greater than the given size then it is set to that size.
 496      * </p>
 497      *
 498      * @param  size
 499      *         The new size, a non-negative byte count
 500      *
 501      * @return  This file channel
 502      *
 503      * @throws  NonWritableChannelException
 504      *          If this channel was not opened for writing
 505      *
 506      * @throws  ClosedChannelException
 507      *          If this channel is closed
 508      *
 509      * @throws  IllegalArgumentException
 510      *          If the new size is negative
 511      *
 512      * @throws  IOException
 513      *          If some other I/O error occurs
 514      */
 515     public abstract FileChannel truncate(long size) throws IOException;
 516 
 517     /**
 518      * Forces any updates to this channel's file to be written to the storage
 519      * device that contains it.
 520      *
 521      * <p> If this channel's file resides on a local storage device then when
 522      * this method returns it is guaranteed that all changes made to the file
 523      * since this channel was created, or since this method was last invoked,
 524      * will have been written to that device.  This is useful for ensuring that
 525      * critical information is not lost in the event of a system crash.
 526      *
 527      * <p> If the file does not reside on a local device then no such guarantee
 528      * is made.
 529      *
 530      * <p> The {@code metaData} parameter can be used to limit the number of
 531      * I/O operations that this method is required to perform.  Passing
 532      * {@code false} for this parameter indicates that only updates to the
 533      * file's content need be written to storage; passing {@code true}
 534      * indicates that updates to both the file's content and metadata must be
 535      * written, which generally requires at least one more I/O operation.
 536      * Whether this parameter actually has any effect is dependent upon the
 537      * underlying operating system and is therefore unspecified.
 538      *
 539      * <p> Invoking this method may cause an I/O operation to occur even if the
 540      * channel was only opened for reading.  Some operating systems, for
 541      * example, maintain a last-access time as part of a file's metadata, and
 542      * this time is updated whenever the file is read.  Whether or not this is
 543      * actually done is system-dependent and is therefore unspecified.
 544      *
 545      * <p> This method is only guaranteed to force changes that were made to
 546      * this channel's file via the methods defined in this class.  It may or
 547      * may not force changes that were made by modifying the content of a
 548      * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by
 549      * invoking the {@link #map map} method.  Invoking the {@link
 550      * MappedByteBuffer#force force} method of the mapped byte buffer will
 551      * force changes made to the buffer's content to be written.  </p>
 552      *
 553      * @param   metaData
 554      *          If {@code true} then this method is required to force changes
 555      *          to both the file's content and metadata to be written to
 556      *          storage; otherwise, it need only force content changes to be
 557      *          written
 558      *
 559      * @throws  ClosedChannelException
 560      *          If this channel is closed
 561      *
 562      * @throws  IOException
 563      *          If some other I/O error occurs
 564      */
 565     public abstract void force(boolean metaData) throws IOException;
 566 
 567     /**
 568      * Transfers bytes from this channel's file to the given writable byte
 569      * channel.
 570      *
 571      * <p> An attempt is made to read up to {@code count} bytes starting at
 572      * the given {@code position} in this channel's file and write them to the
 573      * target channel.  An invocation of this method may or may not transfer
 574      * all of the requested bytes; whether or not it does so depends upon the
 575      * natures and states of the channels.  Fewer than the requested number of
 576      * bytes are transferred if this channel's file contains fewer than
 577      * {@code count} bytes starting at the given {@code position}, or if the
 578      * target channel is non-blocking and it has fewer than {@code count}
 579      * bytes free in its output buffer.
 580      *
 581      * <p> This method does not modify this channel's position.  If the given
 582      * position is greater than the file's current size then no bytes are
 583      * transferred.  If the target channel has a position then bytes are
 584      * written starting at that position and then the position is incremented
 585      * by the number of bytes written.
 586      *
 587      * <p> This method is potentially much more efficient than a simple loop
 588      * that reads from this channel and writes to the target channel.  Many
 589      * operating systems can transfer bytes directly from the filesystem cache
 590      * to the target channel without actually copying them.  </p>
 591      *
 592      * @param  position
 593      *         The position within the file at which the transfer is to begin;
 594      *         must be non-negative
 595      *
 596      * @param  count
 597      *         The maximum number of bytes to be transferred; must be
 598      *         non-negative
 599      *
 600      * @param  target
 601      *         The target channel
 602      *
 603      * @return  The number of bytes, possibly zero,
 604      *          that were actually transferred
 605      *
 606      * @throws IllegalArgumentException
 607      *         If the preconditions on the parameters do not hold
 608      *
 609      * @throws  NonReadableChannelException
 610      *          If this channel was not opened for reading
 611      *
 612      * @throws  NonWritableChannelException
 613      *          If the target channel was not opened for writing
 614      *
 615      * @throws  ClosedChannelException
 616      *          If either this channel or the target channel is closed
 617      *
 618      * @throws  AsynchronousCloseException
 619      *          If another thread closes either channel
 620      *          while the transfer is in progress
 621      *
 622      * @throws  ClosedByInterruptException
 623      *          If another thread interrupts the current thread while the
 624      *          transfer is in progress, thereby closing both channels and
 625      *          setting the current thread's interrupt status
 626      *
 627      * @throws  IOException
 628      *          If some other I/O error occurs
 629      */
 630     public abstract long transferTo(long position, long count,
 631                                     WritableByteChannel target)
 632         throws IOException;
 633 
 634     /**
 635      * Transfers bytes into this channel's file from the given readable byte
 636      * channel.
 637      *
 638      * <p> An attempt is made to read up to {@code count} bytes from the
 639      * source channel and write them to this channel's file starting at the
 640      * given {@code position}.  An invocation of this method may or may not
 641      * transfer all of the requested bytes; whether or not it does so depends
 642      * upon the natures and states of the channels.  Fewer than the requested
 643      * number of bytes will be transferred if the source channel has fewer than
 644      * {@code count} bytes remaining, or if the source channel is non-blocking
 645      * and has fewer than {@code count} bytes immediately available in its
 646      * input buffer.
 647      *
 648      * <p> This method does not modify this channel's position.  If the given
 649      * position is greater than the file's current size then no bytes are
 650      * transferred.  If the source channel has a position then bytes are read
 651      * starting at that position and then the position is incremented by the
 652      * number of bytes read.
 653      *
 654      * <p> This method is potentially much more efficient than a simple loop
 655      * that reads from the source channel and writes to this channel.  Many
 656      * operating systems can transfer bytes directly from the source channel
 657      * into the filesystem cache without actually copying them.  </p>
 658      *
 659      * @param  src
 660      *         The source channel
 661      *
 662      * @param  position
 663      *         The position within the file at which the transfer is to begin;
 664      *         must be non-negative
 665      *
 666      * @param  count
 667      *         The maximum number of bytes to be transferred; must be
 668      *         non-negative
 669      *
 670      * @return  The number of bytes, possibly zero,
 671      *          that were actually transferred
 672      *
 673      * @throws IllegalArgumentException
 674      *         If the preconditions on the parameters do not hold
 675      *
 676      * @throws  NonReadableChannelException
 677      *          If the source channel was not opened for reading
 678      *
 679      * @throws  NonWritableChannelException
 680      *          If this channel was not opened for writing
 681      *
 682      * @throws  ClosedChannelException
 683      *          If either this channel or the source channel is closed
 684      *
 685      * @throws  AsynchronousCloseException
 686      *          If another thread closes either channel
 687      *          while the transfer is in progress
 688      *
 689      * @throws  ClosedByInterruptException
 690      *          If another thread interrupts the current thread while the
 691      *          transfer is in progress, thereby closing both channels and
 692      *          setting the current thread's interrupt status
 693      *
 694      * @throws  IOException
 695      *          If some other I/O error occurs
 696      */
 697     public abstract long transferFrom(ReadableByteChannel src,
 698                                       long position, long count)
 699         throws IOException;
 700 
 701     /**
 702      * Reads a sequence of bytes from this channel into the given buffer,
 703      * starting at the given file position.
 704      *
 705      * <p> This method works in the same manner as the {@link
 706      * #read(ByteBuffer)} method, except that bytes are read starting at the
 707      * given file position rather than at the channel's current position.  This
 708      * method does not modify this channel's position.  If the given position
 709      * is greater than the file's current size then no bytes are read.  </p>
 710      *
 711      * @param  dst
 712      *         The buffer into which bytes are to be transferred
 713      *
 714      * @param  position
 715      *         The file position at which the transfer is to begin;
 716      *         must be non-negative
 717      *
 718      * @return  The number of bytes read, possibly zero, or {@code -1} if the
 719      *          given position is greater than or equal to the file's current
 720      *          size
 721      *
 722      * @throws  IllegalArgumentException
 723      *          If the position is negative
 724      *
 725      * @throws  NonReadableChannelException
 726      *          If this channel was not opened for reading
 727      *
 728      * @throws  ClosedChannelException
 729      *          If this channel is closed
 730      *
 731      * @throws  AsynchronousCloseException
 732      *          If another thread closes this channel
 733      *          while the read operation is in progress
 734      *
 735      * @throws  ClosedByInterruptException
 736      *          If another thread interrupts the current thread
 737      *          while the read operation is in progress, thereby
 738      *          closing the channel and setting the current thread's
 739      *          interrupt status
 740      *
 741      * @throws  IOException
 742      *          If some other I/O error occurs
 743      */
 744     public abstract int read(ByteBuffer dst, long position) throws IOException;
 745 
 746     /**
 747      * Writes a sequence of bytes to this channel from the given buffer,
 748      * starting at the given file position.
 749      *
 750      * <p> This method works in the same manner as the {@link
 751      * #write(ByteBuffer)} method, except that bytes are written starting at
 752      * the given file position rather than at the channel's current position.
 753      * This method does not modify this channel's position.  If the given
 754      * position is greater than the file's current size then the file will be
 755      * grown to accommodate the new bytes; the values of any bytes between the
 756      * previous end-of-file and the newly-written bytes are unspecified.  </p>
 757      *
 758      * @param  src
 759      *         The buffer from which bytes are to be transferred
 760      *
 761      * @param  position
 762      *         The file position at which the transfer is to begin;
 763      *         must be non-negative
 764      *
 765      * @return  The number of bytes written, possibly zero
 766      *
 767      * @throws  IllegalArgumentException
 768      *          If the position is negative
 769      *
 770      * @throws  NonWritableChannelException
 771      *          If this channel was not opened for writing
 772      *
 773      * @throws  ClosedChannelException
 774      *          If this channel is closed
 775      *
 776      * @throws  AsynchronousCloseException
 777      *          If another thread closes this channel
 778      *          while the write operation is in progress
 779      *
 780      * @throws  ClosedByInterruptException
 781      *          If another thread interrupts the current thread
 782      *          while the write operation is in progress, thereby
 783      *          closing the channel and setting the current thread's
 784      *          interrupt status
 785      *
 786      * @throws  IOException
 787      *          If some other I/O error occurs
 788      */
 789     public abstract int write(ByteBuffer src, long position) throws IOException;
 790 
 791 
 792     // -- Memory-mapped buffers --
 793 
 794     /**
 795      * A file-mapping mode.
 796      *
 797      * @since 1.4
 798      *
 799      * @see java.nio.channels.FileChannel#map
 800      */
 801     public static class MapMode {
 802 
 803         /**
 804          * Mode for a read-only mapping.
 805          */
 806         public static final MapMode READ_ONLY
 807             = new MapMode("READ_ONLY");
 808 
 809         /**
 810          * Mode for a read/write mapping.
 811          */
 812         public static final MapMode READ_WRITE
 813             = new MapMode("READ_WRITE");
 814 
 815         /**
 816          * Mode for a private (copy-on-write) mapping.
 817          */
 818         public static final MapMode PRIVATE
 819             = new MapMode("PRIVATE");
 820 
 821         private final String name;
 822 
 823         /**
 824          * Constructs an instance of this class.
 825          * @param name the name of the map mode
 826          * @since 13
 827          */
 828         public MapMode(String name) {
 829             this.name = Objects.requireNonNull(name);
 830         }
 831 
 832         /**
 833          * Returns a string describing this file-mapping mode.
 834          *
 835          * @return  A descriptive string
 836          */
 837         public String toString() {
 838             return name;
 839         }
 840 
 841     }
 842 
 843     /**
 844      * Maps a region of this channel's file directly into memory.
 845      *
 846      * <p> The {@code mode} parameter specifies how the region of the file is
 847      * mapped and may be one of the following modes:
 848      *
 849      * <ul>
 850      *
 851      *   <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer
 852      *   will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.
 853      *   ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>
 854      *
 855      *   <li><p> <i>Read/write:</i> Changes made to the resulting buffer will
 856      *   eventually be propagated to the file; they may or may not be made
 857      *   visible to other programs that have mapped the same file.  ({@link
 858      *   MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>
 859      *
 860      *   <li><p> <i>Private:</i> Changes made to the resulting buffer will not
 861      *   be propagated to the file and will not be visible to other programs
 862      *   that have mapped the same file; instead, they will cause private
 863      *   copies of the modified portions of the buffer to be created.  ({@link
 864      *   MapMode#PRIVATE MapMode.PRIVATE}) </p></li>
 865      *
 866      * </ul>
 867      *
 868      * <p> An implementation may support additional map modes.
 869      *
 870      * <p> For a read-only mapping, this channel must have been opened for
 871      * reading; for a read/write or private mapping, this channel must have
 872      * been opened for both reading and writing.
 873      *
 874      * <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}
 875      * returned by this method will have a position of zero and a limit and
 876      * capacity of {@code size}; its mark will be undefined.  The buffer and
 877      * the mapping that it represents will remain valid until the buffer itself
 878      * is garbage-collected.
 879      *
 880      * <p> A mapping, once established, is not dependent upon the file channel
 881      * that was used to create it.  Closing the channel, in particular, has no
 882      * effect upon the validity of the mapping.
 883      *
 884      * <p> Many of the details of memory-mapped files are inherently dependent
 885      * upon the underlying operating system and are therefore unspecified.  The
 886      * behavior of this method when the requested region is not completely
 887      * contained within this channel's file is unspecified.  Whether changes
 888      * made to the content or size of the underlying file, by this program or
 889      * another, are propagated to the buffer is unspecified.  The rate at which
 890      * changes to the buffer are propagated to the file is unspecified.
 891      *
 892      * <p> For most operating systems, mapping a file into memory is more
 893      * expensive than reading or writing a few tens of kilobytes of data via
 894      * the usual {@link #read read} and {@link #write write} methods.  From the
 895      * standpoint of performance it is generally only worth mapping relatively
 896      * large files into memory.  </p>
 897      *
 898      * @param  mode
 899      *         One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link
 900      *         MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE
 901      *         PRIVATE} defined in the {@link MapMode} class, according to
 902      *         whether the file is to be mapped read-only, read/write, or
 903      *         privately (copy-on-write), respectively, or an implementation
 904      *         specific map mode
 905      *
 906      * @param  position
 907      *         The position within the file at which the mapped region
 908      *         is to start; must be non-negative
 909      *
 910      * @param  size
 911      *         The size of the region to be mapped; must be non-negative and
 912      *         no greater than {@link java.lang.Integer#MAX_VALUE}
 913      *
 914      * @return  The mapped byte buffer
 915      *
 916      * @throws NonReadableChannelException
 917      *         If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} or
 918      *         {@link MapMode#READ_ONLY_SYNC READ_ONLY_SYNC} but
 919      *         this channel was not opened for reading
 920      *
 921      * @throws NonWritableChannelException
 922      *         If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE},
 923      *         {@link MapMode#PRIVATE PRIVATE} or {@link MapMode#READ_WRITE_SYNC READ_WRITE_SYNC}
 924      *         but this channel was not opened for both reading and writing
 925      *
 926      * @throws IllegalArgumentException
 927      *         If the preconditions on the parameters do not hold
 928      *
 929      * @throws UnsupportedOperationException
 930      *         If an unsupported map mode is specified
 931      *
 932      * @throws IOException
 933      *         If some other I/O error occurs
 934      *
 935      * @see java.nio.channels.FileChannel.MapMode
 936      * @see java.nio.MappedByteBuffer
 937      */
 938     public abstract MappedByteBuffer map(MapMode mode, long position, long size)
 939         throws IOException;
 940 
 941 
 942     // -- Locks --
 943 
 944     /**
 945      * Acquires a lock on the given region of this channel's file.
 946      *
 947      * <p> An invocation of this method will block until the region can be
 948      * locked, this channel is closed, or the invoking thread is interrupted,
 949      * whichever comes first.
 950      *
 951      * <p> If this channel is closed by another thread during an invocation of
 952      * this method then an {@link AsynchronousCloseException} will be thrown.
 953      *
 954      * <p> If the invoking thread is interrupted while waiting to acquire the
 955      * lock then its interrupt status will be set and a {@link
 956      * FileLockInterruptionException} will be thrown.  If the invoker's
 957      * interrupt status is set when this method is invoked then that exception
 958      * will be thrown immediately; the thread's interrupt status will not be
 959      * changed.
 960      *
 961      * <p> The region specified by the {@code position} and {@code size}
 962      * parameters need not be contained within, or even overlap, the actual
 963      * underlying file.  Lock regions are fixed in size; if a locked region
 964      * initially contains the end of the file and the file grows beyond the
 965      * region then the new portion of the file will not be covered by the lock.
 966      * If a file is expected to grow in size and a lock on the entire file is
 967      * required then a region starting at zero, and no smaller than the
 968      * expected maximum size of the file, should be locked.  The zero-argument
 969      * {@link #lock()} method simply locks a region of size {@link
 970      * Long#MAX_VALUE}.
 971      *
 972      * <p> Some operating systems do not support shared locks, in which case a
 973      * request for a shared lock is automatically converted into a request for
 974      * an exclusive lock.  Whether the newly-acquired lock is shared or
 975      * exclusive may be tested by invoking the resulting lock object's {@link
 976      * FileLock#isShared() isShared} method.
 977      *
 978      * <p> File locks are held on behalf of the entire Java virtual machine.
 979      * They are not suitable for controlling access to a file by multiple
 980      * threads within the same virtual machine.  </p>
 981      *
 982      * @param  position
 983      *         The position at which the locked region is to start; must be
 984      *         non-negative
 985      *
 986      * @param  size
 987      *         The size of the locked region; must be non-negative, and the sum
 988      *         {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
 989      *
 990      * @param  shared
 991      *         {@code true} to request a shared lock, in which case this
 992      *         channel must be open for reading (and possibly writing);
 993      *         {@code false} to request an exclusive lock, in which case this
 994      *         channel must be open for writing (and possibly reading)
 995      *
 996      * @return  A lock object representing the newly-acquired lock
 997      *
 998      * @throws  IllegalArgumentException
 999      *          If the preconditions on the parameters do not hold
1000      *
1001      * @throws  ClosedChannelException
1002      *          If this channel is closed
1003      *
1004      * @throws  AsynchronousCloseException
1005      *          If another thread closes this channel while the invoking
1006      *          thread is blocked in this method
1007      *
1008      * @throws  FileLockInterruptionException
1009      *          If the invoking thread is interrupted while blocked in this
1010      *          method
1011      *
1012      * @throws  OverlappingFileLockException
1013      *          If a lock that overlaps the requested region is already held by
1014      *          this Java virtual machine, or if another thread is already
1015      *          blocked in this method and is attempting to lock an overlapping
1016      *          region
1017      *
1018      * @throws  NonReadableChannelException
1019      *          If {@code shared} is {@code true} this channel was not
1020      *          opened for reading
1021      *
1022      * @throws  NonWritableChannelException
1023      *          If {@code shared} is {@code false} but this channel was not
1024      *          opened for writing
1025      *
1026      * @throws  IOException
1027      *          If some other I/O error occurs
1028      *
1029      * @see     #lock()
1030      * @see     #tryLock()
1031      * @see     #tryLock(long,long,boolean)
1032      */
1033     public abstract FileLock lock(long position, long size, boolean shared)
1034         throws IOException;
1035 
1036     /**
1037      * Acquires an exclusive lock on this channel's file.
1038      *
1039      * <p> An invocation of this method of the form {@code fc.lock()} behaves
1040      * in exactly the same way as the invocation
1041      *
1042      * <pre>
1043      *     fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>
1044      *
1045      * @return  A lock object representing the newly-acquired lock
1046      *
1047      * @throws  ClosedChannelException
1048      *          If this channel is closed
1049      *
1050      * @throws  AsynchronousCloseException
1051      *          If another thread closes this channel while the invoking
1052      *          thread is blocked in this method
1053      *
1054      * @throws  FileLockInterruptionException
1055      *          If the invoking thread is interrupted while blocked in this
1056      *          method
1057      *
1058      * @throws  OverlappingFileLockException
1059      *          If a lock that overlaps the requested region is already held by
1060      *          this Java virtual machine, or if another thread is already
1061      *          blocked in this method and is attempting to lock an overlapping
1062      *          region of the same file
1063      *
1064      * @throws  NonWritableChannelException
1065      *          If this channel was not opened for writing
1066      *
1067      * @throws  IOException
1068      *          If some other I/O error occurs
1069      *
1070      * @see     #lock(long,long,boolean)
1071      * @see     #tryLock()
1072      * @see     #tryLock(long,long,boolean)
1073      */
1074     public final FileLock lock() throws IOException {
1075         return lock(0L, Long.MAX_VALUE, false);
1076     }
1077 
1078     /**
1079      * Attempts to acquire a lock on the given region of this channel's file.
1080      *
1081      * <p> This method does not block.  An invocation always returns
1082      * immediately, either having acquired a lock on the requested region or
1083      * having failed to do so.  If it fails to acquire a lock because an
1084      * overlapping lock is held by another program then it returns
1085      * {@code null}.  If it fails to acquire a lock for any other reason then
1086      * an appropriate exception is thrown.
1087      *
1088      * <p> The region specified by the {@code position} and {@code size}
1089      * parameters need not be contained within, or even overlap, the actual
1090      * underlying file.  Lock regions are fixed in size; if a locked region
1091      * initially contains the end of the file and the file grows beyond the
1092      * region then the new portion of the file will not be covered by the lock.
1093      * If a file is expected to grow in size and a lock on the entire file is
1094      * required then a region starting at zero, and no smaller than the
1095      * expected maximum size of the file, should be locked.  The zero-argument
1096      * {@link #tryLock()} method simply locks a region of size {@link
1097      * Long#MAX_VALUE}.
1098      *
1099      * <p> Some operating systems do not support shared locks, in which case a
1100      * request for a shared lock is automatically converted into a request for
1101      * an exclusive lock.  Whether the newly-acquired lock is shared or
1102      * exclusive may be tested by invoking the resulting lock object's {@link
1103      * FileLock#isShared() isShared} method.
1104      *
1105      * <p> File locks are held on behalf of the entire Java virtual machine.
1106      * They are not suitable for controlling access to a file by multiple
1107      * threads within the same virtual machine.  </p>
1108      *
1109      * @param  position
1110      *         The position at which the locked region is to start; must be
1111      *         non-negative
1112      *
1113      * @param  size
1114      *         The size of the locked region; must be non-negative, and the sum
1115      *         {@code position}&nbsp;+&nbsp;{@code size} must be non-negative
1116      *
1117      * @param  shared
1118      *         {@code true} to request a shared lock,
1119      *         {@code false} to request an exclusive lock
1120      *
1121      * @return  A lock object representing the newly-acquired lock,
1122      *          or {@code null} if the lock could not be acquired
1123      *          because another program holds an overlapping lock
1124      *
1125      * @throws  IllegalArgumentException
1126      *          If the preconditions on the parameters do not hold
1127      *
1128      * @throws  ClosedChannelException
1129      *          If this channel is closed
1130      *
1131      * @throws  OverlappingFileLockException
1132      *          If a lock that overlaps the requested region is already held by
1133      *          this Java virtual machine, or if another thread is already
1134      *          blocked in this method and is attempting to lock an overlapping
1135      *          region of the same file
1136      *
1137      * @throws  IOException
1138      *          If some other I/O error occurs
1139      *
1140      * @see     #lock()
1141      * @see     #lock(long,long,boolean)
1142      * @see     #tryLock()
1143      */
1144     public abstract FileLock tryLock(long position, long size, boolean shared)
1145         throws IOException;
1146 
1147     /**
1148      * Attempts to acquire an exclusive lock on this channel's file.
1149      *
1150      * <p> An invocation of this method of the form {@code fc.tryLock()}
1151      * behaves in exactly the same way as the invocation
1152      *
1153      * <pre>
1154      *     fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>
1155      *
1156      * @return  A lock object representing the newly-acquired lock,
1157      *          or {@code null} if the lock could not be acquired
1158      *          because another program holds an overlapping lock
1159      *
1160      * @throws  ClosedChannelException
1161      *          If this channel is closed
1162      *
1163      * @throws  OverlappingFileLockException
1164      *          If a lock that overlaps the requested region is already held by
1165      *          this Java virtual machine, or if another thread is already
1166      *          blocked in this method and is attempting to lock an overlapping
1167      *          region
1168      *
1169      * @throws  IOException
1170      *          If some other I/O error occurs
1171      *
1172      * @see     #lock()
1173      * @see     #lock(long,long,boolean)
1174      * @see     #tryLock(long,long,boolean)
1175      */
1176     public final FileLock tryLock() throws IOException {
1177         return tryLock(0L, Long.MAX_VALUE, false);
1178     }
1179 
1180 }