Path: blob/master/src/java.base/share/classes/java/nio/channels/FileChannel.java
41159 views
/*1* Copyright (c) 2000, 2021, 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 {@code read} or {@code write} 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 {@code getChannel} 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 {@code getChannel}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 id="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 {@code "r"} and will be open for reading and writing131* if the instance was created with mode {@code "rw"}.132*133* <a id="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 {@code true} 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 class="striped">177* <caption style="display:none">additional options</caption>178* <thead>179* <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr>180* </thead>181* <tbody>182* <tr>183* <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th>184* <td> If this option is present then the file is opened for writing and185* each invocation of the channel's {@code write} method first advances186* the position to the end of the file and then writes the requested187* data. Whether the advancement of the position and the writing of the188* data are done in a single atomic operation is system-dependent and189* therefore unspecified. This option may not be used in conjunction190* with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td>191* </tr>192* <tr>193* <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th>194* <td> If this option is present then the existing file is truncated to195* a size of 0 bytes. This option is ignored when the file is opened only196* for reading. </td>197* </tr>198* <tr>199* <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th>200* <td> If this option is present then a new file is created, failing if201* the file already exists. When creating a file the check for the202* existence of the file and the creation of the file if it does not exist203* is atomic with respect to other file system operations. This option is204* ignored when the file is opened only for reading. </td>205* </tr>206* <tr>207* <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th>208* <td> If this option is present then an existing file is opened if it209* exists, otherwise a new file is created. When creating a file the check210* for the existence of the file and the creation of the file if it does211* not exist is atomic with respect to other file system operations. This212* option is ignored if the {@code CREATE_NEW} option is also present or213* the file is opened only for reading. </td>214* </tr>215* <tr>216* <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th>217* <td> When this option is present then the implementation makes a218* <em>best effort</em> attempt to delete the file when closed by219* the {@link #close close} method. If the {@code close} method is not220* invoked then a <em>best effort</em> attempt is made to delete the file221* when the Java virtual machine terminates. </td>222* </tr>223* <tr>224* <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th>225* <td> When creating a new file this option is a <em>hint</em> that the226* new file will be sparse. This option is ignored when not creating227* a new file. </td>228* </tr>229* <tr>230* <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th>231* <td> Requires that every update to the file's content or metadata be232* written synchronously to the underlying storage device. (see <a233* href="../file/package-summary.html#integrity"> Synchronized I/O file234* integrity</a>). </td>235* </tr>236* <tr>237* <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th>238* <td> Requires that every update to the file's content be written239* synchronously to the underlying storage device. (see <a240* href="../file/package-summary.html#integrity"> Synchronized I/O file241* integrity</a>). </td>242* </tr>243* </tbody>244* </table>245*246* <p> An implementation may also support additional options.247*248* <p> The {@code attrs} parameter is an optional array of file {@link249* FileAttribute file-attributes} to set atomically when creating the file.250*251* <p> The new channel is created by invoking the {@link252* FileSystemProvider#newFileChannel newFileChannel} method on the253* provider that created the {@code Path}.254*255* @param path256* The path of the file to open or create257* @param options258* Options specifying how the file is opened259* @param attrs260* An optional list of file attributes to set atomically when261* creating the file262*263* @return A new file channel264*265* @throws IllegalArgumentException266* If the set contains an invalid combination of options267* @throws UnsupportedOperationException268* If the {@code path} is associated with a provider that does not269* support creating file channels, or an unsupported open option is270* specified, or the array contains an attribute that cannot be set271* atomically when creating the file272* @throws FileAlreadyExistsException273* If a file of that name already exists and the {@link274* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified275* and the file is being opened for writing276* <i>(<a href="../file/package-summary.html#optspecex">optional277* specific exception</a>)</i>278* @throws IOException279* If an I/O error occurs280* @throws SecurityException281* If a security manager is installed and it denies an282* unspecified permission required by the implementation.283* In the case of the default provider, the {@link284* SecurityManager#checkRead(String)} method is invoked to check285* read access if the file is opened for reading. The {@link286* SecurityManager#checkWrite(String)} method is invoked to check287* write access if the file is opened for writing288*289* @since 1.7290*/291public static FileChannel open(Path path,292Set<? extends OpenOption> options,293FileAttribute<?>... attrs)294throws IOException295{296FileSystemProvider provider = path.getFileSystem().provider();297return provider.newFileChannel(path, options, attrs);298}299300@SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction301private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0];302303/**304* Opens or creates a file, returning a file channel to access the file.305*306* <p> An invocation of this method behaves in exactly the same way as the307* invocation308* <pre>309* fc.{@link #open(Path,Set,FileAttribute[]) open}(file, opts, new FileAttribute<?>[0]);310* </pre>311* where {@code opts} is a set of the options specified in the {@code312* options} array.313*314* @param path315* The path of the file to open or create316* @param options317* Options specifying how the file is opened318*319* @return A new file channel320*321* @throws IllegalArgumentException322* If the set contains an invalid combination of options323* @throws UnsupportedOperationException324* If the {@code path} is associated with a provider that does not325* support creating file channels, or an unsupported open option is326* specified327* @throws FileAlreadyExistsException328* If a file of that name already exists and the {@link329* StandardOpenOption#CREATE_NEW CREATE_NEW} option is specified330* and the file is being opened for writing331* <i>(<a href="../file/package-summary.html#optspecex">optional332* specific exception</a>)</i>333* @throws IOException334* If an I/O error occurs335* @throws SecurityException336* If a security manager is installed and it denies an337* unspecified permission required by the implementation.338* In the case of the default provider, the {@link339* SecurityManager#checkRead(String)} method is invoked to check340* read access if the file is opened for reading. The {@link341* SecurityManager#checkWrite(String)} method is invoked to check342* write access if the file is opened for writing343*344* @since 1.7345*/346public static FileChannel open(Path path, OpenOption... options)347throws IOException348{349Set<OpenOption> set;350if (options.length == 0) {351set = Collections.emptySet();352} else {353set = new HashSet<>();354Collections.addAll(set, options);355}356return open(path, set, NO_ATTRIBUTES);357}358359// -- Channel operations --360361/**362* Reads a sequence of bytes from this channel into the given buffer.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* ReadableByteChannel} interface. </p>368*/369public abstract int read(ByteBuffer dst) throws IOException;370371/**372* Reads a sequence of bytes from this channel into a subsequence of the373* given buffers.374*375* <p> Bytes are read starting at this channel's current file position, and376* then the file position is updated with the number of bytes actually377* read. Otherwise this method behaves exactly as specified in the {@link378* ScatteringByteChannel} interface. </p>379*/380public abstract long read(ByteBuffer[] dsts, int offset, int length)381throws IOException;382383/**384* Reads a sequence of bytes from this channel into the given buffers.385*386* <p> Bytes are read starting at this channel's current file position, and387* then the file position is updated with the number of bytes actually388* read. Otherwise this method behaves exactly as specified in the {@link389* ScatteringByteChannel} interface. </p>390*/391public final long read(ByteBuffer[] dsts) throws IOException {392return read(dsts, 0, dsts.length);393}394395/**396* Writes a sequence of bytes to this channel from the given buffer.397*398* <p> Bytes are written starting at this channel's current file position399* unless the channel is in append mode, in which case the position is400* first advanced to the end of the file. The file is grown, if necessary,401* to accommodate the written bytes, and then the file position is updated402* with the number of bytes actually written. Otherwise this method403* behaves exactly as specified by the {@link WritableByteChannel}404* interface. </p>405*/406public abstract int write(ByteBuffer src) throws IOException;407408/**409* Writes a sequence of bytes to this channel from a subsequence of the410* given buffers.411*412* <p> Bytes are written starting at this channel's current file position413* unless the channel is in append mode, in which case the position is414* first advanced to the end of the file. The file is grown, if necessary,415* to accommodate the written bytes, and then the file position is updated416* with the number of bytes actually written. Otherwise this method417* behaves exactly as specified in the {@link GatheringByteChannel}418* interface. </p>419*/420public abstract long write(ByteBuffer[] srcs, int offset, int length)421throws IOException;422423/**424* Writes a sequence of bytes to this channel from the given buffers.425*426* <p> Bytes are written starting at this channel's current file position427* unless the channel is in append mode, in which case the position is428* first advanced to the end of the file. The file is grown, if necessary,429* to accommodate the written bytes, and then the file position is updated430* with the number of bytes actually written. Otherwise this method431* behaves exactly as specified in the {@link GatheringByteChannel}432* interface. </p>433*/434public final long write(ByteBuffer[] srcs) throws IOException {435return write(srcs, 0, srcs.length);436}437438439// -- Other operations --440441/**442* Returns this channel's file position.443*444* @return This channel's file position,445* a non-negative integer counting the number of bytes446* from the beginning of the file to the current position447*448* @throws ClosedChannelException449* If this channel is closed450*451* @throws IOException452* If some other I/O error occurs453*/454public abstract long position() throws IOException;455456/**457* Sets this channel's file position.458*459* <p> Setting the position to a value that is greater than the file's460* current size is legal but does not change the size of the file. A later461* attempt to read bytes at such a position will immediately return an462* end-of-file indication. A later attempt to write bytes at such a463* position will cause the file to be grown to accommodate the new bytes;464* the values of any bytes between the previous end-of-file and the465* newly-written bytes are unspecified. </p>466*467* @param newPosition468* The new position, a non-negative integer counting469* the number of bytes from the beginning of the file470*471* @return This file channel472*473* @throws ClosedChannelException474* If this channel is closed475*476* @throws IllegalArgumentException477* If the new position is negative478*479* @throws IOException480* If some other I/O error occurs481*/482public abstract FileChannel position(long newPosition) throws IOException;483484/**485* Returns the current size of this channel's file.486*487* @return The current size of this channel's file,488* measured in bytes489*490* @throws ClosedChannelException491* If this channel is closed492*493* @throws IOException494* If some other I/O error occurs495*/496public abstract long size() throws IOException;497498/**499* Truncates this channel's file to the given size.500*501* <p> If the given size is less than the file's current size then the file502* is truncated, discarding any bytes beyond the new end of the file. If503* the given size is greater than or equal to the file's current size then504* the file is not modified. In either case, if this channel's file505* position is greater than the given size then it is set to that size.506* </p>507*508* @param size509* The new size, a non-negative byte count510*511* @return This file channel512*513* @throws NonWritableChannelException514* If this channel was not opened for writing515*516* @throws ClosedChannelException517* If this channel is closed518*519* @throws IllegalArgumentException520* If the new size is negative521*522* @throws IOException523* If some other I/O error occurs524*/525public abstract FileChannel truncate(long size) throws IOException;526527/**528* Forces any updates to this channel's file to be written to the storage529* device that contains it.530*531* <p> If this channel's file resides on a local storage device then when532* this method returns it is guaranteed that all changes made to the file533* since this channel was created, or since this method was last invoked,534* will have been written to that device. This is useful for ensuring that535* critical information is not lost in the event of a system crash.536*537* <p> If the file does not reside on a local device then no such guarantee538* is made.539*540* <p> The {@code metaData} parameter can be used to limit the number of541* I/O operations that this method is required to perform. Passing542* {@code false} for this parameter indicates that only updates to the543* file's content need be written to storage; passing {@code true}544* indicates that updates to both the file's content and metadata must be545* written, which generally requires at least one more I/O operation.546* Whether this parameter actually has any effect is dependent upon the547* underlying operating system and is therefore unspecified.548*549* <p> Invoking this method may cause an I/O operation to occur even if the550* channel was only opened for reading. Some operating systems, for551* example, maintain a last-access time as part of a file's metadata, and552* this time is updated whenever the file is read. Whether or not this is553* actually done is system-dependent and is therefore unspecified.554*555* <p> This method is only guaranteed to force changes that were made to556* this channel's file via the methods defined in this class. It may or557* may not force changes that were made by modifying the content of a558* {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by559* invoking the {@link #map map} method. Invoking the {@link560* MappedByteBuffer#force force} method of the mapped byte buffer will561* force changes made to the buffer's content to be written. </p>562*563* @param metaData564* If {@code true} then this method is required to force changes565* to both the file's content and metadata to be written to566* storage; otherwise, it need only force content changes to be567* written568*569* @throws ClosedChannelException570* If this channel is closed571*572* @throws IOException573* If some other I/O error occurs574*/575public abstract void force(boolean metaData) throws IOException;576577/**578* Transfers bytes from this channel's file to the given writable byte579* channel.580*581* <p> An attempt is made to read up to {@code count} bytes starting at582* the given {@code position} in this channel's file and write them to the583* target channel. An invocation of this method may or may not transfer584* all of the requested bytes; whether or not it does so depends upon the585* natures and states of the channels. Fewer than the requested number of586* bytes are transferred if this channel's file contains fewer than587* {@code count} bytes starting at the given {@code position}, or if the588* target channel is non-blocking and it has fewer than {@code count}589* bytes free in its output buffer.590*591* <p> This method does not modify this channel's position. If the given592* position is greater than the file's current size then no bytes are593* transferred. If the target channel has a position then bytes are594* written starting at that position and then the position is incremented595* by the number of bytes written.596*597* <p> This method is potentially much more efficient than a simple loop598* that reads from this channel and writes to the target channel. Many599* operating systems can transfer bytes directly from the filesystem cache600* to the target channel without actually copying them. </p>601*602* @param position603* The position within the file at which the transfer is to begin;604* must be non-negative605*606* @param count607* The maximum number of bytes to be transferred; must be608* non-negative609*610* @param target611* The target channel612*613* @return The number of bytes, possibly zero,614* that were actually transferred615*616* @throws IllegalArgumentException617* If the preconditions on the parameters do not hold618*619* @throws NonReadableChannelException620* If this channel was not opened for reading621*622* @throws NonWritableChannelException623* If the target channel was not opened for writing624*625* @throws ClosedChannelException626* If either this channel or the target channel is closed627*628* @throws AsynchronousCloseException629* If another thread closes either channel630* while the transfer is in progress631*632* @throws ClosedByInterruptException633* If another thread interrupts the current thread while the634* transfer is in progress, thereby closing both channels and635* setting the current thread's interrupt status636*637* @throws IOException638* If some other I/O error occurs639*/640public abstract long transferTo(long position, long count,641WritableByteChannel target)642throws IOException;643644/**645* Transfers bytes into this channel's file from the given readable byte646* channel.647*648* <p> An attempt is made to read up to {@code count} bytes from the649* source channel and write them to this channel's file starting at the650* given {@code position}. An invocation of this method may or may not651* transfer all of the requested bytes; whether or not it does so depends652* upon the natures and states of the channels. Fewer than the requested653* number of bytes will be transferred if the source channel has fewer than654* {@code count} bytes remaining, or if the source channel is non-blocking655* and has fewer than {@code count} bytes immediately available in its656* input buffer. No bytes are transferred, and zero is returned, if the657* source has reached end-of-stream.658*659* <p> This method does not modify this channel's position. If the given660* position is greater than the file's current size then no bytes are661* transferred. If the source channel has a position then bytes are read662* starting at that position and then the position is incremented by the663* number of bytes read.664*665* <p> This method is potentially much more efficient than a simple loop666* that reads from the source channel and writes to this channel. Many667* operating systems can transfer bytes directly from the source channel668* into the filesystem cache without actually copying them. </p>669*670* @param src671* The source channel672*673* @param position674* The position within the file at which the transfer is to begin;675* must be non-negative676*677* @param count678* The maximum number of bytes to be transferred; must be679* non-negative680*681* @return The number of bytes, possibly zero,682* that were actually transferred683*684* @throws IllegalArgumentException685* If the preconditions on the parameters do not hold686*687* @throws NonReadableChannelException688* If the source channel was not opened for reading689*690* @throws NonWritableChannelException691* If this channel was not opened for writing692*693* @throws ClosedChannelException694* If either this channel or the source channel is closed695*696* @throws AsynchronousCloseException697* If another thread closes either channel698* while the transfer is in progress699*700* @throws ClosedByInterruptException701* If another thread interrupts the current thread while the702* transfer is in progress, thereby closing both channels and703* setting the current thread's interrupt status704*705* @throws IOException706* If some other I/O error occurs707*/708public abstract long transferFrom(ReadableByteChannel src,709long position, long count)710throws IOException;711712/**713* Reads a sequence of bytes from this channel into the given buffer,714* starting at the given file position.715*716* <p> This method works in the same manner as the {@link717* #read(ByteBuffer)} method, except that bytes are read starting at the718* given file position rather than at the channel's current position. This719* method does not modify this channel's position. If the given position720* is greater than the file's current size then no bytes are read. </p>721*722* @param dst723* The buffer into which bytes are to be transferred724*725* @param position726* The file position at which the transfer is to begin;727* must be non-negative728*729* @return The number of bytes read, possibly zero, or {@code -1} if the730* given position is greater than or equal to the file's current731* size732*733* @throws IllegalArgumentException734* If the position is negative or the buffer is read-only735*736* @throws NonReadableChannelException737* If this channel was not opened for reading738*739* @throws ClosedChannelException740* If this channel is closed741*742* @throws AsynchronousCloseException743* If another thread closes this channel744* while the read operation is in progress745*746* @throws ClosedByInterruptException747* If another thread interrupts the current thread748* while the read operation is in progress, thereby749* closing the channel and setting the current thread's750* interrupt status751*752* @throws IOException753* If some other I/O error occurs754*/755public abstract int read(ByteBuffer dst, long position) throws IOException;756757/**758* Writes a sequence of bytes to this channel from the given buffer,759* starting at the given file position.760*761* <p> This method works in the same manner as the {@link762* #write(ByteBuffer)} method, except that bytes are written starting at763* the given file position rather than at the channel's current position.764* This method does not modify this channel's position. If the given765* position is greater than the file's current size then the file will be766* grown to accommodate the new bytes; the values of any bytes between the767* previous end-of-file and the newly-written bytes are unspecified. </p>768*769* @param src770* The buffer from which bytes are to be transferred771*772* @param position773* The file position at which the transfer is to begin;774* must be non-negative775*776* @return The number of bytes written, possibly zero777*778* @throws IllegalArgumentException779* If the position is negative780*781* @throws NonWritableChannelException782* If this channel was not opened for writing783*784* @throws ClosedChannelException785* If this channel is closed786*787* @throws AsynchronousCloseException788* If another thread closes this channel789* while the write operation is in progress790*791* @throws ClosedByInterruptException792* If another thread interrupts the current thread793* while the write operation is in progress, thereby794* closing the channel and setting the current thread's795* interrupt status796*797* @throws IOException798* If some other I/O error occurs799*/800public abstract int write(ByteBuffer src, long position) throws IOException;801802803// -- Memory-mapped buffers --804805/**806* A file-mapping mode.807*808* @since 1.4809*810* @see java.nio.channels.FileChannel#map811*/812public static class MapMode {813814/**815* Mode for a read-only mapping.816*/817public static final MapMode READ_ONLY818= new MapMode("READ_ONLY");819820/**821* Mode for a read/write mapping.822*/823public static final MapMode READ_WRITE824= new MapMode("READ_WRITE");825826/**827* Mode for a private (copy-on-write) mapping.828*/829public static final MapMode PRIVATE830= new MapMode("PRIVATE");831832private final String name;833834/**835* Constructs an instance of this class. This constructor may be used836* by code in java.base to create file mapping modes beyond the file837* mapping modes defined here.838* @param name the name of the map mode839*/840private MapMode(String name) {841this.name = name;842}843844/**845* Returns a string describing this file-mapping mode.846*847* @return A descriptive string848*/849public String toString() {850return name;851}852853}854855/**856* Maps a region of this channel's file directly into memory.857*858* <p> The {@code mode} parameter specifies how the region of the file is859* mapped and may be one of the following modes:860*861* <ul>862*863* <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer864* will cause a {@link java.nio.ReadOnlyBufferException} to be thrown.865* ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li>866*867* <li><p> <i>Read/write:</i> Changes made to the resulting buffer will868* eventually be propagated to the file; they may or may not be made869* visible to other programs that have mapped the same file. ({@link870* MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li>871*872* <li><p> <i>Private:</i> Changes made to the resulting buffer will not873* be propagated to the file and will not be visible to other programs874* that have mapped the same file; instead, they will cause private875* copies of the modified portions of the buffer to be created. ({@link876* MapMode#PRIVATE MapMode.PRIVATE}) </p></li>877*878* </ul>879*880* <p> An implementation may support additional map modes.881*882* <p> For a read-only mapping, this channel must have been opened for883* reading; for a read/write or private mapping, this channel must have884* been opened for both reading and writing.885*886* <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>}887* returned by this method will have a position of zero and a limit and888* capacity of {@code size}; its mark will be undefined. The buffer and889* the mapping that it represents will remain valid until the buffer itself890* is garbage-collected.891*892* <p> A mapping, once established, is not dependent upon the file channel893* that was used to create it. Closing the channel, in particular, has no894* effect upon the validity of the mapping.895*896* <p> Many of the details of memory-mapped files are inherently dependent897* upon the underlying operating system and are therefore unspecified. The898* behavior of this method when the requested region is not completely899* contained within this channel's file is unspecified. Whether changes900* made to the content or size of the underlying file, by this program or901* another, are propagated to the buffer is unspecified. The rate at which902* changes to the buffer are propagated to the file is unspecified.903*904* <p> For most operating systems, mapping a file into memory is more905* expensive than reading or writing a few tens of kilobytes of data via906* the usual {@link #read read} and {@link #write write} methods. From the907* standpoint of performance it is generally only worth mapping relatively908* large files into memory. </p>909*910* @param mode911* One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link912* MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE913* PRIVATE} defined in the {@link MapMode} class, according to914* whether the file is to be mapped read-only, read/write, or915* privately (copy-on-write), respectively, or an implementation916* specific map mode917*918* @param position919* The position within the file at which the mapped region920* is to start; must be non-negative921*922* @param size923* The size of the region to be mapped; must be non-negative and924* no greater than {@link java.lang.Integer#MAX_VALUE}925*926* @return The mapped byte buffer927*928* @throws NonReadableChannelException929* If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} or930* an implementation specific map mode requiring read access931* but this channel was not opened for reading932*933* @throws NonWritableChannelException934* If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE}.935* {@link MapMode#PRIVATE PRIVATE} or an implementation specific936* map mode requiring write access but this channel was not937* opened for both reading and writing938*939* @throws IllegalArgumentException940* If the preconditions on the parameters do not hold941*942* @throws UnsupportedOperationException943* If an unsupported map mode is specified944*945* @throws IOException946* If some other I/O error occurs947*948* @see java.nio.channels.FileChannel.MapMode949* @see java.nio.MappedByteBuffer950*/951public abstract MappedByteBuffer map(MapMode mode, long position, long size)952throws IOException;953954955// -- Locks --956957/**958* Acquires a lock on the given region of this channel's file.959*960* <p> An invocation of this method will block until the region can be961* locked, this channel is closed, or the invoking thread is interrupted,962* whichever comes first.963*964* <p> If this channel is closed by another thread during an invocation of965* this method then an {@link AsynchronousCloseException} will be thrown.966*967* <p> If the invoking thread is interrupted while waiting to acquire the968* lock then its interrupt status will be set and a {@link969* FileLockInterruptionException} will be thrown. If the invoker's970* interrupt status is set when this method is invoked then that exception971* will be thrown immediately; the thread's interrupt status will not be972* changed.973*974* <p> The region specified by the {@code position} and {@code size}975* parameters need not be contained within, or even overlap, the actual976* underlying file. Lock regions are fixed in size; if a locked region977* initially contains the end of the file and the file grows beyond the978* region then the new portion of the file will not be covered by the lock.979* If a file is expected to grow in size and a lock on the entire file is980* required then a region starting at zero, and no smaller than the981* expected maximum size of the file, should be locked. The zero-argument982* {@link #lock()} method simply locks a region of size {@link983* Long#MAX_VALUE}.984*985* <p> Some operating systems do not support shared locks, in which case a986* request for a shared lock is automatically converted into a request for987* an exclusive lock. Whether the newly-acquired lock is shared or988* exclusive may be tested by invoking the resulting lock object's {@link989* FileLock#isShared() isShared} method.990*991* <p> File locks are held on behalf of the entire Java virtual machine.992* They are not suitable for controlling access to a file by multiple993* threads within the same virtual machine. </p>994*995* @param position996* The position at which the locked region is to start; must be997* non-negative998*999* @param size1000* The size of the locked region; must be non-negative, and the sum1001* {@code position} + {@code size} must be non-negative1002*1003* @param shared1004* {@code true} to request a shared lock, in which case this1005* channel must be open for reading (and possibly writing);1006* {@code false} to request an exclusive lock, in which case this1007* channel must be open for writing (and possibly reading)1008*1009* @return A lock object representing the newly-acquired lock1010*1011* @throws IllegalArgumentException1012* If the preconditions on the parameters do not hold1013*1014* @throws ClosedChannelException1015* If this channel is closed1016*1017* @throws AsynchronousCloseException1018* If another thread closes this channel while the invoking1019* thread is blocked in this method1020*1021* @throws FileLockInterruptionException1022* If the invoking thread is interrupted while blocked in this1023* method1024*1025* @throws OverlappingFileLockException1026* If a lock that overlaps the requested region is already held by1027* this Java virtual machine, or if another thread is already1028* blocked in this method and is attempting to lock an overlapping1029* region1030*1031* @throws NonReadableChannelException1032* If {@code shared} is {@code true} this channel was not1033* opened for reading1034*1035* @throws NonWritableChannelException1036* If {@code shared} is {@code false} but this channel was not1037* opened for writing1038*1039* @throws IOException1040* If some other I/O error occurs1041*1042* @see #lock()1043* @see #tryLock()1044* @see #tryLock(long,long,boolean)1045*/1046public abstract FileLock lock(long position, long size, boolean shared)1047throws IOException;10481049/**1050* Acquires an exclusive lock on this channel's file.1051*1052* <p> An invocation of this method of the form {@code fc.lock()} behaves1053* in exactly the same way as the invocation1054*1055* <pre>1056* fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre>1057*1058* @return A lock object representing the newly-acquired lock1059*1060* @throws ClosedChannelException1061* If this channel is closed1062*1063* @throws AsynchronousCloseException1064* If another thread closes this channel while the invoking1065* thread is blocked in this method1066*1067* @throws FileLockInterruptionException1068* If the invoking thread is interrupted while blocked in this1069* method1070*1071* @throws OverlappingFileLockException1072* If a lock that overlaps the requested region is already held by1073* this Java virtual machine, or if another thread is already1074* blocked in this method and is attempting to lock an overlapping1075* region of the same file1076*1077* @throws NonWritableChannelException1078* If this channel was not opened for writing1079*1080* @throws IOException1081* If some other I/O error occurs1082*1083* @see #lock(long,long,boolean)1084* @see #tryLock()1085* @see #tryLock(long,long,boolean)1086*/1087public final FileLock lock() throws IOException {1088return lock(0L, Long.MAX_VALUE, false);1089}10901091/**1092* Attempts to acquire a lock on the given region of this channel's file.1093*1094* <p> This method does not block. An invocation always returns1095* immediately, either having acquired a lock on the requested region or1096* having failed to do so. If it fails to acquire a lock because an1097* overlapping lock is held by another program then it returns1098* {@code null}. If it fails to acquire a lock for any other reason then1099* an appropriate exception is thrown.1100*1101* <p> The region specified by the {@code position} and {@code size}1102* parameters need not be contained within, or even overlap, the actual1103* underlying file. Lock regions are fixed in size; if a locked region1104* initially contains the end of the file and the file grows beyond the1105* region then the new portion of the file will not be covered by the lock.1106* If a file is expected to grow in size and a lock on the entire file is1107* required then a region starting at zero, and no smaller than the1108* expected maximum size of the file, should be locked. The zero-argument1109* {@link #tryLock()} method simply locks a region of size {@link1110* Long#MAX_VALUE}.1111*1112* <p> Some operating systems do not support shared locks, in which case a1113* request for a shared lock is automatically converted into a request for1114* an exclusive lock. Whether the newly-acquired lock is shared or1115* exclusive may be tested by invoking the resulting lock object's {@link1116* FileLock#isShared() isShared} method.1117*1118* <p> File locks are held on behalf of the entire Java virtual machine.1119* They are not suitable for controlling access to a file by multiple1120* threads within the same virtual machine. </p>1121*1122* @param position1123* The position at which the locked region is to start; must be1124* non-negative1125*1126* @param size1127* The size of the locked region; must be non-negative, and the sum1128* {@code position} + {@code size} must be non-negative1129*1130* @param shared1131* {@code true} to request a shared lock,1132* {@code false} to request an exclusive lock1133*1134* @return A lock object representing the newly-acquired lock,1135* or {@code null} if the lock could not be acquired1136* because another program holds an overlapping lock1137*1138* @throws IllegalArgumentException1139* If the preconditions on the parameters do not hold1140*1141* @throws ClosedChannelException1142* If this channel is closed1143*1144* @throws OverlappingFileLockException1145* If a lock that overlaps the requested region is already held by1146* this Java virtual machine, or if another thread is already1147* blocked in this method and is attempting to lock an overlapping1148* region of the same file1149*1150* @throws IOException1151* If some other I/O error occurs1152*1153* @see #lock()1154* @see #lock(long,long,boolean)1155* @see #tryLock()1156*/1157public abstract FileLock tryLock(long position, long size, boolean shared)1158throws IOException;11591160/**1161* Attempts to acquire an exclusive lock on this channel's file.1162*1163* <p> An invocation of this method of the form {@code fc.tryLock()}1164* behaves in exactly the same way as the invocation1165*1166* <pre>1167* fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre>1168*1169* @return A lock object representing the newly-acquired lock,1170* or {@code null} if the lock could not be acquired1171* because another program holds an overlapping lock1172*1173* @throws ClosedChannelException1174* If this channel is closed1175*1176* @throws OverlappingFileLockException1177* If a lock that overlaps the requested region is already held by1178* this Java virtual machine, or if another thread is already1179* blocked in this method and is attempting to lock an overlapping1180* region1181*1182* @throws IOException1183* If some other I/O error occurs1184*1185* @see #lock()1186* @see #lock(long,long,boolean)1187* @see #tryLock(long,long,boolean)1188*/1189public final FileLock tryLock() throws IOException {1190return tryLock(0L, Long.MAX_VALUE, false);1191}11921193}119411951196