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