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