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