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

Save This Page
Home » openjdk-7 » java » nio » channels » [javadoc | source]