Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/FileChannel.java
38918 views
/*1* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.channels;2627import java.io.*;28import java.nio.ByteBuffer;29import java.nio.MappedByteBuffer;30import java.nio.channels.spi.AbstractInterruptibleChannel;31import java.nio.file.*;32import java.nio.file.attribute.FileAttribute;33import java.nio.file.spi.*;34import java.util.Set;35import java.util.HashSet;36import java.util.Collections;3738/**39* A channel for reading, writing, mapping, and manipulating a file.40*41* <p> A file channel is a {@link SeekableByteChannel} that is connected to42* a file. It has a current <i>position</i> within its file which can43* be both {@link #position() <i>queried</i>} and {@link #position(long)44* <i>modified</i>}. The file itself contains a variable-length sequence45* of bytes that can be read and written and whose current {@link #size46* <i>size</i>} can be queried. The size of the file increases47* when bytes are written beyond its current size; the size of the file48* decreases when it is {@link #truncate <i>truncated</i>}. The49* file may also have some associated <i>metadata</i> such as access50* permissions, content type, and last-modification time; this class does not51* define methods for metadata access.52*53* <p> In addition to the familiar read, write, and close operations of byte54* channels, this class defines the following file-specific operations: </p>55*56* <ul>57*58* <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or59* {@link #write(ByteBuffer, long) <i>written</i>} at an absolute60* position in a file in a way that does not affect the channel's current61* position. </p></li>62*63* <li><p> A region of a file may be {@link #map <i>mapped</i>}64* directly into memory; for large files this is often much more efficient65* than invoking the usual <tt>read</tt> or <tt>write</tt> methods.66* </p></li>67*68* <li><p> Updates made to a file may be {@link #force <i>forced69* out</i>} to the underlying storage device, ensuring that data are not70* lost in the event of a system crash. </p></li>71*72* <li><p> Bytes can be transferred from a file {@link #transferTo <i>to73* some other channel</i>}, and {@link #transferFrom <i>vice74* versa</i>}, in a way that can be optimized by many operating systems75* into a very fast transfer directly to or from the filesystem cache.76* </p></li>77*78* <li><p> A region of a file may be {@link FileLock <i>locked</i>}79* against access by other programs. </p></li>80*81* </ul>82*83* <p> File channels are safe for use by multiple concurrent threads. The84* {@link Channel#close close} method may be invoked at any time, as specified85* by the {@link Channel} interface. Only one operation that involves the86* channel's position or can change its file's size may be in progress at any87* given time; attempts to initiate a second such operation while the first is88* still in progress will block until the first operation completes. Other89* operations, in particular those that take an explicit position, may proceed90* concurrently; whether they in fact do so is dependent upon the underlying91* implementation and is therefore unspecified.92*93* <p> The view of a file provided by an instance of this class is guaranteed94* to be consistent with other views of the same file provided by other95* instances in the same program. The view provided by an instance of this96* class may or may not, however, be consistent with the views seen by other97* concurrently-running programs due to caching performed by the underlying98* operating system and delays induced by network-filesystem protocols. This99* is true regardless of the language in which these other programs are100* written, and whether they are running on the same machine or on some other101* machine. The exact nature of any such inconsistencies are system-dependent102* and are therefore unspecified.103*104* <p> A file channel is created by invoking one of the {@link #open open}105* methods defined by this class. A file channel can also be obtained from an106* existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link107* java.io.FileOutputStream#getChannel FileOutputStream}, or {@link108* java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking109* that object's <tt>getChannel</tt> method, which returns a file channel that110* is connected to the same underlying file. Where the file channel is obtained111* from an existing stream or random access file then the state of the file112* channel is intimately connected to that of the object whose <tt>getChannel</tt>113* method returned the channel. Changing the channel's position, whether114* explicitly or by reading or writing bytes, will change the file position of115* the originating object, and vice versa. Changing the file's length via the116* file channel will change the length seen via the originating object, and vice117* versa. Changing the file's content by writing bytes will change the content118* seen by the originating object, and vice versa.119*120* <a name="open-mode"></a> <p> At various points this class specifies that an121* instance that is "open for reading," "open for writing," or "open for122* reading and writing" is required. A channel obtained via the {@link123* java.io.FileInputStream#getChannel getChannel} method of a {@link124* java.io.FileInputStream} instance will be open for reading. A channel125* obtained via the {@link java.io.FileOutputStream#getChannel getChannel}126* method of a {@link java.io.FileOutputStream} instance will be open for127* writing. Finally, a channel obtained via the {@link128* java.io.RandomAccessFile#getChannel getChannel} method of a {@link129* java.io.RandomAccessFile} instance will be open for reading if the instance130* was created with mode <tt>"r"</tt> and will be open for reading and writing131* if the instance was created with mode <tt>"rw"</tt>.132*133* <a name="append-mode"></a><p> A file channel that is open for writing may be in134* <i>append mode</i>, for example if it was obtained from a file-output stream135* that was created by invoking the {@link136* java.io.FileOutputStream#FileOutputStream(java.io.File,boolean)137* FileOutputStream(File,boolean)} constructor and passing <tt>true</tt> for138* the second parameter. In this mode each invocation of a relative write139* operation first advances the position to the end of the file and then writes140* the requested data. Whether the advancement of the position and the writing141* of the data are done in a single atomic operation is system-dependent and142* therefore unspecified.143*144* @see java.io.FileInputStream#getChannel()145* @see java.io.FileOutputStream#getChannel()146* @see java.io.RandomAccessFile#getChannel()147*148* @author Mark Reinhold149* @author Mike McCloskey150* @author JSR-51 Expert Group151* @since 1.4152*/153154public abstract class FileChannel155extends AbstractInterruptibleChannel156implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel157{158/**159* Initializes a new instance of this class.160*/161protected FileChannel() { }162163/**164* Opens or creates a file, returning a file channel to access the file.165*166* <p> The {@code options} parameter determines how the file is opened.167* The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE168* WRITE} options determine if the file should be opened for reading and/or169* writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND}170* option) is contained in the array then the file is opened for reading.171* By default reading or writing commences at the beginning of the file.172*173* <p> In the addition to {@code READ} and {@code WRITE}, the following174* options may be present:175*176* <table border=1 cellpadding=5 summary="">177* <tr> <th>Option</th> <th>Description</th> </tr>178* <tr>179* <td> {@link StandardOpenOption#APPEND APPEND} </td>180* <td> If this option is present then the file is opened for writing and181* each invocation of the channel's {@code write} method first advances182* the position to the end of the file and then writes the requested183* data. Whether the advancement of the position and the writing of the184* data are done in a single atomic operation is system-dependent and185* therefore unspecified. This option may not be used in conjunction186* with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>187* </tr>188* <tr>189* <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td>190* <td> If this option is present then the existing file is truncated to191* a size of 0 bytes. This option is ignored when the file is opened only192* for reading. </td>193* </tr>194* <tr>195* <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td>196* <td> If this option is present then a new file is created, failing if197* the file already exists. When creating a file the check for the198* existence of the file and the creation of the file if it does not exist199* is atomic with respect to other file system operations. This option is200* ignored when the file is opened only for reading. </td>201* </tr>202* <tr>203* <td > {@link StandardOpenOption#CREATE CREATE} </td>204* <td> If this option is present then an existing file is opened if it205* exists, otherwise a new file is created. When creating a file the check206* for the existence of the file and the creation of the file if it does207* not exist is atomic with respect to other file system operations. This208* option is ignored if the {@code CREATE_NEW} option is also present or209* the file is opened only for reading. </td>210* </tr>211* <tr>212* <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td>213* <td> When this option is present then the implementation makes a214* <em>best effort</em> attempt to delete the file when closed by the215* the {@link #close close} method. If the {@code close} method is not216* invoked then a <em>best effort</em> attempt is made to delete the file217* when the Java virtual machine terminates. </td>218* </tr>219* <tr>220* <td>{@link StandardOpenOption#SPARSE SPARSE} </td>221* <td> When creating a new file this option is a <em>hint</em> that the222* new file will be sparse. This option is ignored when not creating223* a new file. </td>224* </tr>225* <tr>226* <td> {@link StandardOpenOption#SYNC SYNC} </td>227* <td> Requires that every update to the file's content or metadata be228* written synchronously to the underlying storage device. (see <a229* href="../file/package-summary.html#integrity"> Synchronized I/O file230* integrity</a>). </td>231* </tr>232* <tr>233* <td> {@link StandardOpenOption#DSYNC DSYNC} </td>234* <td> Requires that every update to the file's content be written235* synchronously to the underlying storage device. (see <a236* href="../file/package-summary.html#integrity"> Synchronized I/O file237* integrity</a>). </td>238* </tr>239* </table>240*241* <p> An implementation may also support additional options.242*243* <p> The {@code attrs} parameter is an optional array of file {@link244* FileAttribute file-attributes} to set atomically when creating the file.245*246* <p> The new channel is created by invoking the {@link247* FileSystemProvider#newFileChannel newFileChannel} method on the248* provider that created the {@code Path}.249*250* @param path251* The path of the file to open or create252* @param options253* Options specifying how the file is opened254* @param attrs255* An optional list of file attributes to set atomically when256* creating the file257*258* @return A new file channel259*260* @throws IllegalArgumentException261* If the set contains an invalid combination of options262* @throws UnsupportedOperationException263* If the {@code path} is associated with a provider that does not264* support creating file channels, or an unsupported open option is265* specified, or the array contains an attribute that cannot be set266* atomically when creating the file267* @throws IOException268* If an I/O error occurs269* @throws SecurityException270* If a security manager is installed and it denies an271* unspecified permission required by the implementation.272* In the case of the default provider, the {@link273* SecurityManager#checkRead(String)} method is invoked to check274* read access if the file is opened for reading. The {@link275* SecurityManager#checkWrite(String)} method is invoked to check276* write access if the file is opened for writing277*278* @since 1.7279*/280public static FileChannel open(Path path,281Set<? extends OpenOption> options,282FileAttribute<?>... attrs)283throws IOException284{285FileSystemProvider provider = path.getFileSystem().provider();286return provider.newFileChannel(path, options, attrs);287}288289@SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction290private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];291292/**293* Opens or creates a file, returning a file channel to access the file.294*295* <p> An invocation of this method behaves in exactly the same way as the296* invocation297* <pre>298* fc.{@link #open(Path,Set,FileAttribute[]) open}(file, opts, new FileAttribute<?>[0]);299* </pre>300* where {@code opts} is a set of the options specified in the {@code301* options} array.302*303* @param path304* The path of the file to open or create305* @param options306* Options specifying how the file is opened307*308* @return A new file channel309*310* @throws IllegalArgumentException311* If the set contains an invalid combination of options312* @throws UnsupportedOperationException313* If the {@code path} is associated with a provider that does not314* support creating file channels, or an unsupported open option is315* specified316* @throws IOException317* If an I/O error occurs318* @throws SecurityException319* If a security manager is installed and it denies an320* unspecified permission required by the implementation.321* In the case of the default provider, the {@link322* SecurityManager#checkRead(String)} method is invoked to check323* read access if the file is opened for reading. The {@link324* SecurityManager#checkWrite(String)} method is invoked to check325* write access if the file is opened for writing326*327* @since 1.7328*/329public static FileChannel open(Path path, OpenOption... options)330throws IOException331{332Set<OpenOption> set = new HashSet<OpenOption>(options.length);333Collections.addAll(set, options);334return open(path, set, NO_ATTRIBUTES);335}336337// -- Channel operations --338339/**340* Reads a sequence of bytes from this channel into the given buffer.341*342* <p> Bytes are read starting at this channel's current file position, and343* then the file position is updated with the number of bytes actually344* read. Otherwise this method behaves exactly as specified in the {@link345* ReadableByteChannel} interface. </p>346*/347public abstract int read(ByteBuffer dst) throws IOException;348349/**350* Reads a sequence of bytes from this channel into a subsequence of the351* given buffers.352*353* <p> Bytes are read starting at this channel's current file position, and354* then the file position is updated with the number of bytes actually355* read. Otherwise this method behaves exactly as specified in the {@link356* ScatteringByteChannel} interface. </p>357*/358public abstract long read(ByteBuffer[] dsts, int offset, int length)359throws IOException;360361/**362* Reads a sequence of bytes from this channel into the given buffers.363*364* <p> Bytes are read starting at this channel's current file position, and365* then the file position is updated with the number of bytes actually366* read. Otherwise this method behaves exactly as specified in the {@link367* ScatteringByteChannel} interface. </p>368*/369public final long read(ByteBuffer[] dsts) throws IOException {370return read(dsts, 0, dsts.length);371}372373/**374* Writes a sequence of bytes to this channel from the given buffer.375*376* <p> Bytes are written starting at this channel's current file position377* unless the channel is in append mode, in which case the position is378* first advanced to the end of the file. The file is grown, if necessary,379* to accommodate the written bytes, and then the file position is updated380* with the number of bytes actually written. Otherwise this method381* behaves exactly as specified by the {@link WritableByteChannel}382* interface. </p>383*/384public abstract int write(ByteBuffer src) throws IOException;385386/**387* Writes a sequence of bytes to this channel from a subsequence of the388* given buffers.389*390* <p> Bytes are written starting at this channel's current file position391* unless the channel is in append mode, in which case the position is392* first advanced to the end of the file. The file is grown, if necessary,393* to accommodate the written bytes, and then the file position is updated394* with the number of bytes actually written. Otherwise this method395* behaves exactly as specified in the {@link GatheringByteChannel}396* interface. </p>397*/398public abstract long write(ByteBuffer[] srcs, int offset, int length)399throws IOException;400401/**402* Writes a sequence of bytes to this channel from the given buffers.403*404* <p> Bytes are written starting at this channel's current file position405* unless the channel is in append mode, in which case the position is406* first advanced to the end of the file. The file is grown, if necessary,407* to accommodate the written bytes, and then the file position is updated408* with the number of bytes actually written. Otherwise this method409* behaves exactly as specified in the {@link GatheringByteChannel}410* interface. </p>411*/412public final long write(ByteBuffer[] srcs) throws IOException {413return write(srcs, 0, srcs.length);414}415416417// -- Other operations --418419/**420* Returns this channel's file position.421*422* @return This channel's file position,423* a non-negative integer counting the number of bytes424* from the beginning of the file to the current position425*426* @throws ClosedChannelException427* If this channel is closed428*429* @throws IOException430* If some other I/O error occurs431*/432public abstract long position() throws IOException;433434/**435* Sets this channel's file position.436*437* <p> Setting the position to a value that is greater than the file's438* current size is legal but does not change the size of the file. A later439* attempt to read bytes at such a position will immediately return an440* end-of-file indication. A later attempt to write bytes at such a441* position will cause the file to be grown to accommodate the new bytes;442* the values of any bytes between the previous end-of-file and the443* newly-written bytes are unspecified. </p>444*445* @param newPosition446* The new position, a non-negative integer counting447* the number of bytes from the beginning of the file448*449* @return This file channel450*451* @throws ClosedChannelException452* If this channel is closed453*454* @throws IllegalArgumentException455* If the new position is negative456*457* @throws IOException458* If some other I/O error occurs459*/460public abstract FileChannel position(long newPosition) throws IOException;461462/**463* Returns the current size of this channel's file.464*465* @return The current size of this channel's file,466* measured in bytes467*468* @throws ClosedChannelException469* If this channel is closed470*471* @throws IOException472* If some other I/O error occurs473*/474public abstract long size() throws IOException;475476/**477* Truncates this channel's file to the given size.478*479* <p> If the given size is less than the file's current size then the file480* is truncated, discarding any bytes beyond the new end of the file. If481* the given size is greater than or equal to the file's current size then482* the file is not modified. In either case, if this channel's file483* position is greater than the given size then it is set to that size.484* </p>485*486* @param size487* The new size, a non-negative byte count488*489* @return This file channel490*491* @throws NonWritableChannelException492* If this channel was not opened for writing493*494* @throws ClosedChannelException495* If this channel is closed496*497* @throws IllegalArgumentException498* If the new size is negative499*500* @throws IOException501* If some other I/O error occurs502*/503public abstract FileChannel truncate(long size) throws IOException;504505/**506* Forces any updates to this channel's file to be written to the storage507* device that contains it.508*509* <p> If this channel's file resides on a local storage device then when510* this method returns it is guaranteed that all changes made to the file511* since this channel was created, or since this method was last invoked,512* will have been written to that device. This is useful for ensuring that513* critical information is not lost in the event of a system crash.514*515* <p> If the file does not reside on a local device then no such guarantee516* is made.517*518* <p> The <tt>metaData</tt> parameter can be used to limit the number of519* I/O operations that this method is required to perform. Passing520* <tt>false</tt> for this parameter indicates that only updates to the521* file's content need be written to storage; passing <tt>true</tt>522* indicates that updates to both the file's content and metadata must be523* written, which generally requires at least one more I/O operation.524* Whether this parameter actually has any effect is dependent upon the525* underlying operating system and is therefore unspecified.526*527* <p> Invoking this method may cause an I/O operation to occur even if the528* channel was only opened for reading. Some operating systems, for529* example, maintain a last-access time as part of a file's metadata, and530* this time is updated whenever the file is read. Whether or not this is531* actually done is system-dependent and is therefore unspecified.532*533* <p> This method is only guaranteed to force changes that were made to534* this channel's file via the methods defined in this class. It may or535* may not force changes that were made by modifying the content of a536* {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by537* invoking the {@link #map map} method. Invoking the {@link538* MappedByteBuffer#force force} method of the mapped byte buffer will539* force changes made to the buffer's content to be written. </p>540*541* @param metaData542* If <tt>true</tt> then this method is required to force changes543* to both the file's content and metadata to be written to544* storage; otherwise, it need only force content changes to be545* written546*547* @throws ClosedChannelException548* If this channel is closed549*550* @throws IOException551* If some other I/O error occurs552*/553public abstract void force(boolean metaData) throws IOException;554555/**556* Transfers bytes from this channel's file to the given writable byte557* channel.558*559* <p> An attempt is made to read up to <tt>count</tt> bytes starting at560* the given <tt>position</tt> in this channel's file and write them to the561* target channel. An invocation of this method may or may not transfer562* all of the requested bytes; whether or not it does so depends upon the563* natures and states of the channels. Fewer than the requested number of564* bytes are transferred if this channel's file contains fewer than565* <tt>count</tt> bytes starting at the given <tt>position</tt>, or if the566* target channel is non-blocking and it has fewer than <tt>count</tt>567* bytes free in its output buffer.568*569* <p> This method does not modify this channel's position. If the given570* position is greater than the file's current size then no bytes are571* transferred. If the target channel has a position then bytes are572* written starting at that position and then the position is incremented573* by the number of bytes written.574*575* <p> This method is potentially much more efficient than a simple loop576* that reads from this channel and writes to the target channel. Many577* operating systems can transfer bytes directly from the filesystem cache578* to the target channel without actually copying them. </p>579*580* @param position581* The position within the file at which the transfer is to begin;582* must be non-negative583*584* @param count585* The maximum number of bytes to be transferred; must be586* non-negative587*588* @param target589* The target channel590*591* @return The number of bytes, possibly zero,592* that were actually transferred593*594* @throws IllegalArgumentException595* If the preconditions on the parameters do not hold596*597* @throws NonReadableChannelException598* If this channel was not opened for reading599*600* @throws NonWritableChannelException601* If the target channel was not opened for writing602*603* @throws ClosedChannelException604* If either this channel or the target channel is closed605*606* @throws AsynchronousCloseException607* If another thread closes either channel608* while the transfer is in progress609*610* @throws ClosedByInterruptException611* If another thread interrupts the current thread while the612* transfer is in progress, thereby closing both channels and613* setting the current thread's interrupt status614*615* @throws IOException616* If some other I/O error occurs617*/618public abstract long transferTo(long position, long count,619WritableByteChannel target)620throws IOException;621622/**623* Transfers bytes into this channel's file from the given readable byte624* channel.625*626* <p> An attempt is made to read up to <tt>count</tt> bytes from the627* source channel and write them to this channel's file starting at the628* given <tt>position</tt>. An invocation of this method may or may not629* transfer all of the requested bytes; whether or not it does so depends630* upon the natures and states of the channels. Fewer than the requested631* number of bytes will be transferred if the source channel has fewer than632* <tt>count</tt> bytes remaining, or if the source channel is non-blocking633* and has fewer than <tt>count</tt> bytes immediately available in its634* input buffer.635*636* <p> This method does not modify this channel's position. If the given637* position is greater than the file's current size then no bytes are638* transferred. If the source channel has a position then bytes are read639* starting at that position and then the position is incremented by the640* number of bytes read.641*642* <p> This method is potentially much more efficient than a simple loop643* that reads from the source channel and writes to this channel. Many644* operating systems can transfer bytes directly from the source channel645* into the filesystem cache without actually copying them. </p>646*647* @param src648* The source channel649*650* @param position651* The position within the file at which the transfer is to begin;652* must be non-negative653*654* @param count655* The maximum number of bytes to be transferred; must be656* non-negative657*658* @return The number of bytes, possibly zero,659* that were actually transferred660*661* @throws IllegalArgumentException662* If the preconditions on the parameters do not hold663*664* @throws NonReadableChannelException665* If the source channel was not opened for reading666*667* @throws NonWritableChannelException668* If this channel was not opened for writing669*670* @throws ClosedChannelException671* If either this channel or the source channel is closed672*673* @throws AsynchronousCloseException674* If another thread closes either channel675* while the transfer is in progress676*677* @throws ClosedByInterruptException678* If another thread interrupts the current thread while the679* transfer is in progress, thereby closing both channels and680* setting the current thread's interrupt status681*682* @throws IOException683* If some other I/O error occurs684*/685public abstract long transferFrom(ReadableByteChannel src,686long position, long count)687throws IOException;688689/**690* Reads a sequence of bytes from this channel into the given buffer,691* starting at the given file position.692*693* <p> This method works in the same manner as the {@link694* #read(ByteBuffer)} method, except that bytes are read starting at the695* given file position rather than at the channel's current position. This696* method does not modify this channel's position. If the given position697* is greater than the file's current size then no bytes are read. </p>698*699* @param dst700* The buffer into which bytes are to be transferred701*702* @param position703* The file position at which the transfer is to begin;704* must be non-negative705*706* @return The number of bytes read, possibly zero, or <tt>-1</tt> if the707* given position is greater than or equal to the file's current708* size709*710* @throws IllegalArgumentException711* If the position is negative712*713* @throws NonReadableChannelException714* If this channel was not opened for reading715*716* @throws ClosedChannelException717* If this channel is closed718*719* @throws AsynchronousCloseException720* If another thread closes this channel721* while the read operation is in progress722*723* @throws ClosedByInterruptException724* If another thread interrupts the current thread725* while the read operation is in progress, thereby726* closing the channel and setting the current thread's727* interrupt status728*729* @throws IOException730* If some other I/O error occurs731*/732public abstract int read(ByteBuffer dst, long position) throws IOException;733734/**735* Writes a sequence of bytes to this channel from the given buffer,736* starting at the given file position.737*738* <p> This method works in the same manner as the {@link739* #write(ByteBuffer)} method, except that bytes are written starting at740* the given file position rather than at the channel's current position.741* This method does not modify this channel's position. If the given742* position is greater than the file's current size then the file will be743* grown to accommodate the new bytes; the values of any bytes between the744* previous end-of-file and the newly-written bytes are unspecified. </p>745*746* @param src747* The buffer from which bytes are to be transferred748*749* @param position750* The file position at which the transfer is to begin;751* must be non-negative752*753* @return The number of bytes written, possibly zero754*755* @throws IllegalArgumentException756* If the position is negative757*758* @throws NonWritableChannelException759* If this channel was not opened for writing760*761* @throws ClosedChannelException762* If this channel is closed763*764* @throws AsynchronousCloseException765* If another thread closes this channel766* while the write operation is in progress767*768* @throws ClosedByInterruptException769* If another thread interrupts the current thread770* while the write operation is in progress, thereby771* closing the channel and setting the current thread's772* interrupt status773*774* @throws IOException775* If some other I/O error occurs776*/777public abstract int write(ByteBuffer src, long position) throws IOException;778779780// -- Memory-mapped buffers --781782/**783* A typesafe enumeration for file-mapping modes.784*785* @since 1.4786*787* @see java.nio.channels.FileChannel#map788*/789public static class MapMode {790791/**792* Mode for a read-only mapping.793*/794public static final MapMode READ_ONLY795= new MapMode("READ_ONLY");796797/**798* Mode for a read/write mapping.799*/800public static final MapMode READ_WRITE801= new MapMode("READ_WRITE");802803/**804* Mode for a private (copy-on-write) mapping.805*/806public static final MapMode PRIVATE807= new MapMode("PRIVATE");808809private final String name;810811private MapMode(String name) {812this.name = name;813}814815/**816* Returns a string describing this file-mapping mode.817*818* @return A descriptive string819*/820public String toString() {821return name;822}823824}825826/**827* Maps a region of this channel's file directly into memory.828*829* <p> A region of a file may be mapped into memory in one of three modes:830* </p>831*832* <ul>833*834* <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer835* will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.836* ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>837*838* <li><p> <i>Read/write:</i> Changes made to the resulting buffer will839* eventually be propagated to the file; they may or may not be made840* visible to other programs that have mapped the same file. ({@link841* MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>842*843* <li><p> <i>Private:</i> Changes made to the resulting buffer will not844* be propagated to the file and will not be visible to other programs845* that have mapped the same file; instead, they will cause private846* copies of the modified portions of the buffer to be created. ({@link847* MapMode#PRIVATE MapMode.PRIVATE}) </p></li>848*849* </ul>850*851* <p> For a read-only mapping, this channel must have been opened for852* reading; for a read/write or private mapping, this channel must have853* been opened for both reading and writing.854*855* <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}856* returned by this method will have a position of zero and a limit and857* capacity of <tt>size</tt>; its mark will be undefined. The buffer and858* the mapping that it represents will remain valid until the buffer itself859* is garbage-collected.860*861* <p> A mapping, once established, is not dependent upon the file channel862* that was used to create it. Closing the channel, in particular, has no863* effect upon the validity of the mapping.864*865* <p> Many of the details of memory-mapped files are inherently dependent866* upon the underlying operating system and are therefore unspecified. The867* behavior of this method when the requested region is not completely868* contained within this channel's file is unspecified. Whether changes869* made to the content or size of the underlying file, by this program or870* another, are propagated to the buffer is unspecified. The rate at which871* changes to the buffer are propagated to the file is unspecified.872*873* <p> For most operating systems, mapping a file into memory is more874* expensive than reading or writing a few tens of kilobytes of data via875* the usual {@link #read read} and {@link #write write} methods. From the876* standpoint of performance it is generally only worth mapping relatively877* large files into memory. </p>878*879* @param mode880* One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link881* MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE882* PRIVATE} defined in the {@link MapMode} class, according to883* whether the file is to be mapped read-only, read/write, or884* privately (copy-on-write), respectively885*886* @param position887* The position within the file at which the mapped region888* is to start; must be non-negative889*890* @param size891* The size of the region to be mapped; must be non-negative and892* no greater than {@link java.lang.Integer#MAX_VALUE}893*894* @return The mapped byte buffer895*896* @throws NonReadableChannelException897* If the <tt>mode</tt> is {@link MapMode#READ_ONLY READ_ONLY} but898* this channel was not opened for reading899*900* @throws NonWritableChannelException901* If the <tt>mode</tt> is {@link MapMode#READ_WRITE READ_WRITE} or902* {@link MapMode#PRIVATE PRIVATE} but this channel was not opened903* for both reading and writing904*905* @throws IllegalArgumentException906* If the preconditions on the parameters do not hold907*908* @throws IOException909* If some other I/O error occurs910*911* @see java.nio.channels.FileChannel.MapMode912* @see java.nio.MappedByteBuffer913*/914public abstract MappedByteBuffer map(MapMode mode,915long position, long size)916throws IOException;917918919// -- Locks --920921/**922* Acquires a lock on the given region of this channel's file.923*924* <p> An invocation of this method will block until the region can be925* locked, this channel is closed, or the invoking thread is interrupted,926* whichever comes first.927*928* <p> If this channel is closed by another thread during an invocation of929* this method then an {@link AsynchronousCloseException} will be thrown.930*931* <p> If the invoking thread is interrupted while waiting to acquire the932* lock then its interrupt status will be set and a {@link933* FileLockInterruptionException} will be thrown. If the invoker's934* interrupt status is set when this method is invoked then that exception935* will be thrown immediately; the thread's interrupt status will not be936* changed.937*938* <p> The region specified by the <tt>position</tt> and <tt>size</tt>939* parameters need not be contained within, or even overlap, the actual940* underlying file. Lock regions are fixed in size; if a locked region941* initially contains the end of the file and the file grows beyond the942* region then the new portion of the file will not be covered by the lock.943* If a file is expected to grow in size and a lock on the entire file is944* required then a region starting at zero, and no smaller than the945* expected maximum size of the file, should be locked. The zero-argument946* {@link #lock()} method simply locks a region of size {@link947* Long#MAX_VALUE}.948*949* <p> Some operating systems do not support shared locks, in which case a950* request for a shared lock is automatically converted into a request for951* an exclusive lock. Whether the newly-acquired lock is shared or952* exclusive may be tested by invoking the resulting lock object's {@link953* FileLock#isShared() isShared} method.954*955* <p> File locks are held on behalf of the entire Java virtual machine.956* They are not suitable for controlling access to a file by multiple957* threads within the same virtual machine. </p>958*959* @param position960* The position at which the locked region is to start; must be961* non-negative962*963* @param size964* The size of the locked region; must be non-negative, and the sum965* <tt>position</tt> + <tt>size</tt> must be non-negative966*967* @param shared968* <tt>true</tt> to request a shared lock, in which case this969* channel must be open for reading (and possibly writing);970* <tt>false</tt> to request an exclusive lock, in which case this971* channel must be open for writing (and possibly reading)972*973* @return A lock object representing the newly-acquired lock974*975* @throws IllegalArgumentException976* If the preconditions on the parameters do not hold977*978* @throws ClosedChannelException979* If this channel is closed980*981* @throws AsynchronousCloseException982* If another thread closes this channel while the invoking983* thread is blocked in this method984*985* @throws FileLockInterruptionException986* If the invoking thread is interrupted while blocked in this987* method988*989* @throws OverlappingFileLockException990* If a lock that overlaps the requested region is already held by991* this Java virtual machine, or if another thread is already992* blocked in this method and is attempting to lock an overlapping993* region994*995* @throws NonReadableChannelException996* If <tt>shared</tt> is <tt>true</tt> this channel was not997* opened for reading998*999* @throws NonWritableChannelException1000* If <tt>shared</tt> is <tt>false</tt> but this channel was not1001* opened for writing1002*1003* @throws IOException1004* If some other I/O error occurs1005*1006* @see #lock()1007* @see #tryLock()1008* @see #tryLock(long,long,boolean)1009*/1010public abstract FileLock lock(long position, long size, boolean shared)1011throws IOException;10121013/**1014* Acquires an exclusive lock on this channel's file.1015*1016* <p> An invocation of this method of the form <tt>fc.lock()</tt> behaves1017* in exactly the same way as the invocation1018*1019* <pre>1020* fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>1021*1022* @return A lock object representing the newly-acquired lock1023*1024* @throws ClosedChannelException1025* If this channel is closed1026*1027* @throws AsynchronousCloseException1028* If another thread closes this channel while the invoking1029* thread is blocked in this method1030*1031* @throws FileLockInterruptionException1032* If the invoking thread is interrupted while blocked in this1033* method1034*1035* @throws OverlappingFileLockException1036* If a lock that overlaps the requested region is already held by1037* this Java virtual machine, or if another thread is already1038* blocked in this method and is attempting to lock an overlapping1039* region of the same file1040*1041* @throws NonWritableChannelException1042* If this channel was not opened for writing1043*1044* @throws IOException1045* If some other I/O error occurs1046*1047* @see #lock(long,long,boolean)1048* @see #tryLock()1049* @see #tryLock(long,long,boolean)1050*/1051public final FileLock lock() throws IOException {1052return lock(0L, Long.MAX_VALUE, false);1053}10541055/**1056* Attempts to acquire a lock on the given region of this channel's file.1057*1058* <p> This method does not block. An invocation always returns1059* immediately, either having acquired a lock on the requested region or1060* having failed to do so. If it fails to acquire a lock because an1061* overlapping lock is held by another program then it returns1062* <tt>null</tt>. If it fails to acquire a lock for any other reason then1063* an appropriate exception is thrown.1064*1065* <p> The region specified by the <tt>position</tt> and <tt>size</tt>1066* parameters need not be contained within, or even overlap, the actual1067* underlying file. Lock regions are fixed in size; if a locked region1068* initially contains the end of the file and the file grows beyond the1069* region then the new portion of the file will not be covered by the lock.1070* If a file is expected to grow in size and a lock on the entire file is1071* required then a region starting at zero, and no smaller than the1072* expected maximum size of the file, should be locked. The zero-argument1073* {@link #tryLock()} method simply locks a region of size {@link1074* Long#MAX_VALUE}.1075*1076* <p> Some operating systems do not support shared locks, in which case a1077* request for a shared lock is automatically converted into a request for1078* an exclusive lock. Whether the newly-acquired lock is shared or1079* exclusive may be tested by invoking the resulting lock object's {@link1080* FileLock#isShared() isShared} method.1081*1082* <p> File locks are held on behalf of the entire Java virtual machine.1083* They are not suitable for controlling access to a file by multiple1084* threads within the same virtual machine. </p>1085*1086* @param position1087* The position at which the locked region is to start; must be1088* non-negative1089*1090* @param size1091* The size of the locked region; must be non-negative, and the sum1092* <tt>position</tt> + <tt>size</tt> must be non-negative1093*1094* @param shared1095* <tt>true</tt> to request a shared lock,1096* <tt>false</tt> to request an exclusive lock1097*1098* @return A lock object representing the newly-acquired lock,1099* or <tt>null</tt> if the lock could not be acquired1100* because another program holds an overlapping lock1101*1102* @throws IllegalArgumentException1103* If the preconditions on the parameters do not hold1104*1105* @throws ClosedChannelException1106* If this channel is closed1107*1108* @throws OverlappingFileLockException1109* If a lock that overlaps the requested region is already held by1110* this Java virtual machine, or if another thread is already1111* blocked in this method and is attempting to lock an overlapping1112* region of the same file1113*1114* @throws IOException1115* If some other I/O error occurs1116*1117* @see #lock()1118* @see #lock(long,long,boolean)1119* @see #tryLock()1120*/1121public abstract FileLock tryLock(long position, long size, boolean shared)1122throws IOException;11231124/**1125* Attempts to acquire an exclusive lock on this channel's file.1126*1127* <p> An invocation of this method of the form <tt>fc.tryLock()</tt>1128* behaves in exactly the same way as the invocation1129*1130* <pre>1131* fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>1132*1133* @return A lock object representing the newly-acquired lock,1134* or <tt>null</tt> if the lock could not be acquired1135* because another program holds an overlapping lock1136*1137* @throws ClosedChannelException1138* If this channel is closed1139*1140* @throws OverlappingFileLockException1141* If a lock that overlaps the requested region is already held by1142* this Java virtual machine, or if another thread is already1143* blocked in this method and is attempting to lock an overlapping1144* region1145*1146* @throws IOException1147* If some other I/O error occurs1148*1149* @see #lock()1150* @see #lock(long,long,boolean)1151* @see #tryLock(long,long,boolean)1152*/1153public final FileLock tryLock() throws IOException {1154return tryLock(0L, Long.MAX_VALUE, false);1155}11561157}115811591160