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