FileChannel.java revision 51b1b6997fd3f980076b8081f7f1165ccc2a4008
1/* 2 * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package java.nio.channels; 27 28import java.io.*; 29import java.nio.ByteBuffer; 30import java.nio.MappedByteBuffer; 31import java.nio.channels.spi.AbstractInterruptibleChannel; 32import java.nio.file.*; 33import java.nio.file.attribute.FileAttribute; 34import java.nio.file.spi.*; 35import java.util.Set; 36import java.util.HashSet; 37import java.util.Collections; 38 39/** 40 * A channel for reading, writing, mapping, and manipulating a file. 41 * 42 * <p> A file channel is a {@link SeekableByteChannel} that is connected to 43 * a file. It has a current <i>position</i> within its file which can 44 * be both {@link #position() <i>queried</i>} and {@link #position(long) 45 * <i>modified</i>}. The file itself contains a variable-length sequence 46 * of bytes that can be read and written and whose current {@link #size 47 * <i>size</i>} can be queried. The size of the file increases 48 * when bytes are written beyond its current size; the size of the file 49 * decreases when it is {@link #truncate </code><i>truncated</i><code>}. The 50 * file may also have some associated <i>metadata</i> such as access 51 * permissions, content type, and last-modification time; this class does not 52 * define methods for metadata access. 53 * 54 * <p> In addition to the familiar read, write, and close operations of byte 55 * channels, this class defines the following file-specific operations: </p> 56 * 57 * <ul> 58 * 59 * <li><p> Bytes may be {@link #read(ByteBuffer, long) read} or 60 * {@link #write(ByteBuffer, long) <i>written</i>} at an absolute 61 * position in a file in a way that does not affect the channel's current 62 * position. </p></li> 63 * 64 * <li><p> A region of a file may be {@link #map <i>mapped</i>} 65 * directly into memory; for large files this is often much more efficient 66 * than invoking the usual <tt>read</tt> or <tt>write</tt> methods. 67 * </p></li> 68 * 69 * <li><p> Updates made to a file may be {@link #force <i>forced 70 * out</i>} to the underlying storage device, ensuring that data are not 71 * lost in the event of a system crash. </p></li> 72 * 73 * <li><p> Bytes can be transferred from a file {@link #transferTo <i>to 74 * some other channel</i>}, and {@link #transferFrom <i>vice 75 * versa</i>}, in a way that can be optimized by many operating systems 76 * into a very fast transfer directly to or from the filesystem cache. 77 * </p></li> 78 * 79 * <li><p> A region of a file may be {@link FileLock <i>locked</i>} 80 * against access by other programs. </p></li> 81 * 82 * </ul> 83 * 84 * <p> File channels are safe for use by multiple concurrent threads. The 85 * {@link Channel#close close} method may be invoked at any time, as specified 86 * by the {@link Channel} interface. Only one operation that involves the 87 * channel's position or can change its file's size may be in progress at any 88 * given time; attempts to initiate a second such operation while the first is 89 * still in progress will block until the first operation completes. Other 90 * operations, in particular those that take an explicit position, may proceed 91 * concurrently; whether they in fact do so is dependent upon the underlying 92 * implementation and is therefore unspecified. 93 * 94 * <p> The view of a file provided by an instance of this class is guaranteed 95 * to be consistent with other views of the same file provided by other 96 * instances in the same program. The view provided by an instance of this 97 * class may or may not, however, be consistent with the views seen by other 98 * concurrently-running programs due to caching performed by the underlying 99 * operating system and delays induced by network-filesystem protocols. This 100 * is true regardless of the language in which these other programs are 101 * written, and whether they are running on the same machine or on some other 102 * machine. The exact nature of any such inconsistencies are system-dependent 103 * and are therefore unspecified. 104 * 105 * <p> A file channel is created by invoking one of the {@link #open open} 106 * methods defined by this class. A file channel can also be obtained from an 107 * existing {@link java.io.FileInputStream#getChannel FileInputStream}, {@link 108 * java.io.FileOutputStream#getChannel FileOutputStream}, or {@link 109 * java.io.RandomAccessFile#getChannel RandomAccessFile} object by invoking 110 * that object's <tt>getChannel</tt> method, which returns a file channel that 111 * is connected to the same underlying file. Where the file channel is obtained 112 * from an existing stream or random access file then the state of the file 113 * channel is intimately connected to that of the object whose <tt>getChannel</tt> 114 * method returned the channel. Changing the channel's position, whether 115 * explicitly or by reading or writing bytes, will change the file position of 116 * the originating object, and vice versa. Changing the file's length via the 117 * file channel will change the length seen via the originating object, and vice 118 * versa. Changing the file's content by writing bytes will change the content 119 * seen by the originating object, and vice versa. 120 * 121 * <a name="open-mode"></a> <p> At various points this class specifies that an 122 * instance that is "open for reading," "open for writing," or "open for 123 * reading and writing" is required. A channel obtained via the {@link 124 * java.io.FileInputStream#getChannel getChannel} method of a {@link 125 * java.io.FileInputStream} instance will be open for reading. A channel 126 * obtained via the {@link java.io.FileOutputStream#getChannel getChannel} 127 * method of a {@link java.io.FileOutputStream} instance will be open for 128 * writing. Finally, a channel obtained via the {@link 129 * java.io.RandomAccessFile#getChannel getChannel} method of a {@link 130 * java.io.RandomAccessFile} instance will be open for reading if the instance 131 * was created with mode <tt>"r"</tt> and will be open for reading and writing 132 * if the instance was created with mode <tt>"rw"</tt>. 133 * 134 * <a name="append-mode"></a><p> A file channel that is open for writing may be in 135 * <i>append mode</i>, for example if it was obtained from a file-output stream 136 * that was created by invoking the {@link 137 * java.io.FileOutputStream#FileOutputStream(java.io.File,boolean) 138 * FileOutputStream(File,boolean)} constructor and passing <tt>true</tt> for 139 * the second parameter. In this mode each invocation of a relative write 140 * operation first advances the position to the end of the file and then writes 141 * the requested data. Whether the advancement of the position and the writing 142 * of the data are done in a single atomic operation is system-dependent and 143 * therefore unspecified. 144 * 145 * @see java.io.FileInputStream#getChannel() 146 * @see java.io.FileOutputStream#getChannel() 147 * @see java.io.RandomAccessFile#getChannel() 148 * 149 * @author Mark Reinhold 150 * @author Mike McCloskey 151 * @author JSR-51 Expert Group 152 * @since 1.4 153 */ 154 155public abstract class FileChannel 156 extends AbstractInterruptibleChannel 157 implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel 158{ 159 /** 160 * Initializes a new instance of this class. 161 */ 162 protected FileChannel() { } 163 164 /** 165 * Opens or creates a file, returning a file channel to access the file. 166 * 167 * <p> The {@code options} parameter determines how the file is opened. 168 * The {@link StandardOpenOption#READ READ} and {@link StandardOpenOption#WRITE 169 * WRITE} options determine if the file should be opened for reading and/or 170 * writing. If neither option (or the {@link StandardOpenOption#APPEND APPEND} 171 * option) is contained in the array then the file is opened for reading. 172 * By default reading or writing commences at the beginning of the file. 173 * 174 * <p> In the addition to {@code READ} and {@code WRITE}, the following 175 * options may be present: 176 * 177 * <table border=1 cellpadding=5 summary=""> 178 * <tr> <th>Option</th> <th>Description</th> </tr> 179 * <tr> 180 * <td> {@link StandardOpenOption#APPEND APPEND} </td> 181 * <td> If this option is present then the file is opened for writing and 182 * each invocation of the channel's {@code write} method first advances 183 * the position to the end of the file and then writes the requested 184 * data. Whether the advancement of the position and the writing of the 185 * data are done in a single atomic operation is system-dependent and 186 * therefore unspecified. This option may not be used in conjunction 187 * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> 188 * </tr> 189 * <tr> 190 * <td> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </td> 191 * <td> If this option is present then the existing file is truncated to 192 * a size of 0 bytes. This option is ignored when the file is opened only 193 * for reading. </td> 194 * </tr> 195 * <tr> 196 * <td> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </td> 197 * <td> If this option is present then a new file is created, failing if 198 * the file already exists. When creating a file the check for the 199 * existence of the file and the creation of the file if it does not exist 200 * is atomic with respect to other file system operations. This option is 201 * ignored when the file is opened only for reading. </td> 202 * </tr> 203 * <tr> 204 * <td > {@link StandardOpenOption#CREATE CREATE} </td> 205 * <td> If this option is present then an existing file is opened if it 206 * exists, otherwise a new file is created. When creating a file the check 207 * for the existence of the file and the creation of the file if it does 208 * not exist is atomic with respect to other file system operations. This 209 * option is ignored if the {@code CREATE_NEW} option is also present or 210 * the file is opened only for reading. </td> 211 * </tr> 212 * <tr> 213 * <td > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </td> 214 * <td> When this option is present then the implementation makes a 215 * <em>best effort</em> attempt to delete the file when closed by the 216 * the {@link #close close} method. If the {@code close} method is not 217 * invoked then a <em>best effort</em> attempt is made to delete the file 218 * when the Java virtual machine terminates. </td> 219 * </tr> 220 * <tr> 221 * <td>{@link StandardOpenOption#SPARSE SPARSE} </td> 222 * <td> When creating a new file this option is a <em>hint</em> that the 223 * new file will be sparse. This option is ignored when not creating 224 * a new file. </td> 225 * </tr> 226 * <tr> 227 * <td> {@link StandardOpenOption#SYNC SYNC} </td> 228 * <td> Requires that every update to the file's content or metadata be 229 * written synchronously to the underlying storage device. (see <a 230 * href="../file/package-summary.html#integrity"> Synchronized I/O file 231 * integrity</a>). </td> 232 * <tr> 233 * <tr> 234 * <td> {@link StandardOpenOption#DSYNC DSYNC} </td> 235 * <td> Requires that every update to the file's content be written 236 * synchronously to the underlying storage device. (see <a 237 * href="../file/package-summary.html#integrity"> Synchronized I/O file 238 * integrity</a>). </td> 239 * </tr> 240 * </table> 241 * 242 * <p> An implementation may also support additional options. 243 * 244 * <p> The {@code attrs} parameter is an optional array of file {@link 245 * FileAttribute file-attributes} to set atomically when creating the file. 246 * 247 * <p> The new channel is created by invoking the {@link 248 * FileSystemProvider#newFileChannel newFileChannel} method on the 249 * provider that created the {@code Path}. 250 * 251 * @param path 252 * The path of the file to open or create 253 * @param options 254 * Options specifying how the file is opened 255 * @param attrs 256 * An optional list of file attributes to set atomically when 257 * creating the file 258 * 259 * @return A new file channel 260 * 261 * @throws IllegalArgumentException 262 * If the set contains an invalid combination of options 263 * @throws UnsupportedOperationException 264 * If the {@code path} is associated with a provider that does not 265 * support creating file channels, or an unsupported open option is 266 * specified, or the array contains an attribute that cannot be set 267 * atomically when creating the file 268 * @throws IOException 269 * If an I/O error occurs 270 * @throws SecurityException 271 * If a security manager is installed and it denies an 272 * unspecified permission required by the implementation. 273 * In the case of the default provider, the {@link 274 * SecurityManager#checkRead(String)} method is invoked to check 275 * read access if the file is opened for reading. The {@link 276 * SecurityManager#checkWrite(String)} method is invoked to check 277 * write access if the file is opened for writing 278 * 279 * @since 1.7 280 */ 281 public static FileChannel open(Path path, 282 Set<? extends OpenOption> options, 283 FileAttribute<?>... attrs) 284 throws IOException 285 { 286 FileSystemProvider provider = path.getFileSystem().provider(); 287 return provider.newFileChannel(path, options, attrs); 288 } 289 290 private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; 291 292 /** 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 the 296 * invocation 297 * <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 {@code 301 * options} array. 302 * 303 * @param path 304 * The path of the file to open or create 305 * @param options 306 * Options specifying how the file is opened 307 * 308 * @return A new file channel 309 * 310 * @throws IllegalArgumentException 311 * If the set contains an invalid combination of options 312 * @throws UnsupportedOperationException 313 * If the {@code path} is associated with a provider that does not 314 * support creating file channels, or an unsupported open option is 315 * specified 316 * @throws IOException 317 * If an I/O error occurs 318 * @throws SecurityException 319 * If a security manager is installed and it denies an 320 * unspecified permission required by the implementation. 321 * In the case of the default provider, the {@link 322 * SecurityManager#checkRead(String)} method is invoked to check 323 * read access if the file is opened for reading. The {@link 324 * SecurityManager#checkWrite(String)} method is invoked to check 325 * write access if the file is opened for writing 326 * 327 * @since 1.7 328 */ 329 public static FileChannel open(Path path, OpenOption... options) 330 throws IOException 331 { 332 Set<OpenOption> set = new HashSet<OpenOption>(options.length); 333 Collections.addAll(set, options); 334 return open(path, set, NO_ATTRIBUTES); 335 } 336 337 // -- Channel operations -- 338 339 /** 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, and 343 * then the file position is updated with the number of bytes actually 344 * read. Otherwise this method behaves exactly as specified in the {@link 345 * ReadableByteChannel} interface. </p> 346 */ 347 public abstract int read(ByteBuffer dst) throws IOException; 348 349 /** 350 * Reads a sequence of bytes from this channel into a subsequence of the 351 * given buffers. 352 * 353 * <p> Bytes are read starting at this channel's current file position, and 354 * then the file position is updated with the number of bytes actually 355 * read. Otherwise this method behaves exactly as specified in the {@link 356 * ScatteringByteChannel} interface. </p> 357 */ 358 public abstract long read(ByteBuffer[] dsts, int offset, int length) 359 throws IOException; 360 361 /** 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, and 365 * then the file position is updated with the number of bytes actually 366 * read. Otherwise this method behaves exactly as specified in the {@link 367 * ScatteringByteChannel} interface. </p> 368 */ 369 public final long read(ByteBuffer[] dsts) throws IOException { 370 return read(dsts, 0, dsts.length); 371 } 372 373 /** 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 position 377 * unless the channel is in append mode, in which case the position is 378 * 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 updated 380 * with the number of bytes actually written. Otherwise this method 381 * behaves exactly as specified by the {@link WritableByteChannel} 382 * interface. </p> 383 */ 384 public abstract int write(ByteBuffer src) throws IOException; 385 386 /** 387 * Writes a sequence of bytes to this channel from a subsequence of the 388 * given buffers. 389 * 390 * <p> Bytes are written starting at this channel's current file position 391 * unless the channel is in append mode, in which case the position is 392 * 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 updated 394 * with the number of bytes actually written. Otherwise this method 395 * behaves exactly as specified in the {@link GatheringByteChannel} 396 * interface. </p> 397 */ 398 public abstract long write(ByteBuffer[] srcs, int offset, int length) 399 throws IOException; 400 401 /** 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 position 405 * unless the channel is in append mode, in which case the position is 406 * 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 updated 408 * with the number of bytes actually written. Otherwise this method 409 * behaves exactly as specified in the {@link GatheringByteChannel} 410 * interface. </p> 411 */ 412 public final long write(ByteBuffer[] srcs) throws IOException { 413 return write(srcs, 0, srcs.length); 414 } 415 416 417 // -- Other operations -- 418 419 /** 420 * Returns this channel's file position. </p> 421 * 422 * @return This channel's file position, 423 * a non-negative integer counting the number of bytes 424 * from the beginning of the file to the current position 425 * 426 * @throws ClosedChannelException 427 * If this channel is closed 428 * 429 * @throws IOException 430 * If some other I/O error occurs 431 */ 432 public abstract long position() throws IOException; 433 434 /** 435 * Sets this channel's file position. 436 * 437 * <p> Setting the position to a value that is greater than the file's 438 * current size is legal but does not change the size of the file. A later 439 * attempt to read bytes at such a position will immediately return an 440 * end-of-file indication. A later attempt to write bytes at such a 441 * 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 the 443 * newly-written bytes are unspecified. </p> 444 * 445 * @param newPosition 446 * The new position, a non-negative integer counting 447 * the number of bytes from the beginning of the file 448 * 449 * @return This file channel 450 * 451 * @throws ClosedChannelException 452 * If this channel is closed 453 * 454 * @throws IllegalArgumentException 455 * If the new position is negative 456 * 457 * @throws IOException 458 * If some other I/O error occurs 459 */ 460 public abstract FileChannel position(long newPosition) throws IOException; 461 462 /** 463 * Returns the current size of this channel's file. </p> 464 * 465 * @return The current size of this channel's file, 466 * measured in bytes 467 * 468 * @throws ClosedChannelException 469 * If this channel is closed 470 * 471 * @throws IOException 472 * If some other I/O error occurs 473 */ 474 public abstract long size() throws IOException; 475 476 /** 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 file 480 * is truncated, discarding any bytes beyond the new end of the file. If 481 * the given size is greater than or equal to the file's current size then 482 * the file is not modified. In either case, if this channel's file 483 * position is greater than the given size then it is set to that size. 484 * </p> 485 * 486 * @param size 487 * The new size, a non-negative byte count 488 * 489 * @return This file channel 490 * 491 * @throws NonWritableChannelException 492 * If this channel was not opened for writing 493 * 494 * @throws ClosedChannelException 495 * If this channel is closed 496 * 497 * @throws IllegalArgumentException 498 * If the new size is negative 499 * 500 * @throws IOException 501 * If some other I/O error occurs 502 */ 503 public abstract FileChannel truncate(long size) throws IOException; 504 505 /** 506 * Forces any updates to this channel's file to be written to the storage 507 * device that contains it. 508 * 509 * <p> If this channel's file resides on a local storage device then when 510 * this method returns it is guaranteed that all changes made to the file 511 * 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 that 513 * 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 guarantee 516 * is made. 517 * 518 * <p> The <tt>metaData</tt> parameter can be used to limit the number of 519 * I/O operations that this method is required to perform. Passing 520 * <tt>false</tt> for this parameter indicates that only updates to the 521 * 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 be 523 * written, which generally requires at least one more I/O operation. 524 * Whether this parameter actually has any effect is dependent upon the 525 * underlying operating system and is therefore unspecified. 526 * 527 * <p> Invoking this method may cause an I/O operation to occur even if the 528 * channel was only opened for reading. Some operating systems, for 529 * example, maintain a last-access time as part of a file's metadata, and 530 * this time is updated whenever the file is read. Whether or not this is 531 * actually done is system-dependent and is therefore unspecified. 532 * 533 * <p> This method is only guaranteed to force changes that were made to 534 * this channel's file via the methods defined in this class. It may or 535 * may not force changes that were made by modifying the content of a 536 * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by 537 * invoking the {@link #map map} method. Invoking the {@link 538 * MappedByteBuffer#force force} method of the mapped byte buffer will 539 * force changes made to the buffer's content to be written. </p> 540 * 541 * @param metaData 542 * If <tt>true</tt> then this method is required to force changes 543 * to both the file's content and metadata to be written to 544 * storage; otherwise, it need only force content changes to be 545 * written 546 * 547 * @throws ClosedChannelException 548 * If this channel is closed 549 * 550 * @throws IOException 551 * If some other I/O error occurs 552 */ 553 public abstract void force(boolean metaData) throws IOException; 554 555 /** 556 * Transfers bytes from this channel's file to the given writable byte 557 * channel. 558 * 559 * <p> An attempt is made to read up to <tt>count</tt> bytes starting at 560 * the given <tt>position</tt> in this channel's file and write them to the 561 * target channel. An invocation of this method may or may not transfer 562 * all of the requested bytes; whether or not it does so depends upon the 563 * natures and states of the channels. Fewer than the requested number of 564 * bytes are transferred if this channel's file contains fewer than 565 * <tt>count</tt> bytes starting at the given <tt>position</tt>, or if the 566 * 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 given 570 * position is greater than the file's current size then no bytes are 571 * transferred. If the target channel has a position then bytes are 572 * written starting at that position and then the position is incremented 573 * by the number of bytes written. 574 * 575 * <p> This method is potentially much more efficient than a simple loop 576 * that reads from this channel and writes to the target channel. Many 577 * operating systems can transfer bytes directly from the filesystem cache 578 * to the target channel without actually copying them. </p> 579 * 580 * @param position 581 * The position within the file at which the transfer is to begin; 582 * must be non-negative 583 * 584 * @param count 585 * The maximum number of bytes to be transferred; must be 586 * non-negative 587 * 588 * @param target 589 * The target channel 590 * 591 * @return The number of bytes, possibly zero, 592 * that were actually transferred 593 * 594 * @throws IllegalArgumentException 595 * If the preconditions on the parameters do not hold 596 * 597 * @throws NonReadableChannelException 598 * If this channel was not opened for reading 599 * 600 * @throws NonWritableChannelException 601 * If the target channel was not opened for writing 602 * 603 * @throws ClosedChannelException 604 * If either this channel or the target channel is closed 605 * 606 * @throws AsynchronousCloseException 607 * If another thread closes either channel 608 * while the transfer is in progress 609 * 610 * @throws ClosedByInterruptException 611 * If another thread interrupts the current thread while the 612 * transfer is in progress, thereby closing both channels and 613 * setting the current thread's interrupt status 614 * 615 * @throws IOException 616 * If some other I/O error occurs 617 */ 618 public abstract long transferTo(long position, long count, 619 WritableByteChannel target) 620 throws IOException; 621 622 /** 623 * Transfers bytes into this channel's file from the given readable byte 624 * channel. 625 * 626 * <p> An attempt is made to read up to <tt>count</tt> bytes from the 627 * source channel and write them to this channel's file starting at the 628 * given <tt>position</tt>. An invocation of this method may or may not 629 * transfer all of the requested bytes; whether or not it does so depends 630 * upon the natures and states of the channels. Fewer than the requested 631 * number of bytes will be transferred if the source channel has fewer than 632 * <tt>count</tt> bytes remaining, or if the source channel is non-blocking 633 * and has fewer than <tt>count</tt> bytes immediately available in its 634 * input buffer. 635 * 636 * <p> This method does not modify this channel's position. If the given 637 * position is greater than the file's current size then no bytes are 638 * transferred. If the source channel has a position then bytes are read 639 * starting at that position and then the position is incremented by the 640 * number of bytes read. 641 * 642 * <p> This method is potentially much more efficient than a simple loop 643 * that reads from the source channel and writes to this channel. Many 644 * operating systems can transfer bytes directly from the source channel 645 * into the filesystem cache without actually copying them. </p> 646 * 647 * @param src 648 * The source channel 649 * 650 * @param position 651 * The position within the file at which the transfer is to begin; 652 * must be non-negative 653 * 654 * @param count 655 * The maximum number of bytes to be transferred; must be 656 * non-negative 657 * 658 * @return The number of bytes, possibly zero, 659 * that were actually transferred 660 * 661 * @throws IllegalArgumentException 662 * If the preconditions on the parameters do not hold 663 * 664 * @throws NonReadableChannelException 665 * If the source channel was not opened for reading 666 * 667 * @throws NonWritableChannelException 668 * If this channel was not opened for writing 669 * 670 * @throws ClosedChannelException 671 * If either this channel or the source channel is closed 672 * 673 * @throws AsynchronousCloseException 674 * If another thread closes either channel 675 * while the transfer is in progress 676 * 677 * @throws ClosedByInterruptException 678 * If another thread interrupts the current thread while the 679 * transfer is in progress, thereby closing both channels and 680 * setting the current thread's interrupt status 681 * 682 * @throws IOException 683 * If some other I/O error occurs 684 */ 685 public abstract long transferFrom(ReadableByteChannel src, 686 long position, long count) 687 throws IOException; 688 689 /** 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 {@link 694 * #read(ByteBuffer)} method, except that bytes are read starting at the 695 * given file position rather than at the channel's current position. This 696 * method does not modify this channel's position. If the given position 697 * is greater than the file's current size then no bytes are read. </p> 698 * 699 * @param dst 700 * The buffer into which bytes are to be transferred 701 * 702 * @param position 703 * The file position at which the transfer is to begin; 704 * must be non-negative 705 * 706 * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the 707 * given position is greater than or equal to the file's current 708 * size 709 * 710 * @throws IllegalArgumentException 711 * If the position is negative 712 * 713 * @throws NonReadableChannelException 714 * If this channel was not opened for reading 715 * 716 * @throws ClosedChannelException 717 * If this channel is closed 718 * 719 * @throws AsynchronousCloseException 720 * If another thread closes this channel 721 * while the read operation is in progress 722 * 723 * @throws ClosedByInterruptException 724 * If another thread interrupts the current thread 725 * while the read operation is in progress, thereby 726 * closing the channel and setting the current thread's 727 * interrupt status 728 * 729 * @throws IOException 730 * If some other I/O error occurs 731 */ 732 public abstract int read(ByteBuffer dst, long position) throws IOException; 733 734 /** 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 {@link 739 * #write(ByteBuffer)} method, except that bytes are written starting at 740 * the given file position rather than at the channel's current position. 741 * This method does not modify this channel's position. If the given 742 * position is greater than the file's current size then the file will be 743 * grown to accommodate the new bytes; the values of any bytes between the 744 * previous end-of-file and the newly-written bytes are unspecified. </p> 745 * 746 * @param src 747 * The buffer from which bytes are to be transferred 748 * 749 * @param position 750 * The file position at which the transfer is to begin; 751 * must be non-negative 752 * 753 * @return The number of bytes written, possibly zero 754 * 755 * @throws IllegalArgumentException 756 * If the position is negative 757 * 758 * @throws NonWritableChannelException 759 * If this channel was not opened for writing 760 * 761 * @throws ClosedChannelException 762 * If this channel is closed 763 * 764 * @throws AsynchronousCloseException 765 * If another thread closes this channel 766 * while the write operation is in progress 767 * 768 * @throws ClosedByInterruptException 769 * If another thread interrupts the current thread 770 * while the write operation is in progress, thereby 771 * closing the channel and setting the current thread's 772 * interrupt status 773 * 774 * @throws IOException 775 * If some other I/O error occurs 776 */ 777 public abstract int write(ByteBuffer src, long position) throws IOException; 778 779 780 // -- Memory-mapped buffers -- 781 782 /** 783 * A typesafe enumeration for file-mapping modes. 784 * 785 * @since 1.4 786 * 787 * @see java.nio.channels.FileChannel#map 788 */ 789 public static class MapMode { 790 791 /** 792 * Mode for a read-only mapping. 793 */ 794 public static final MapMode READ_ONLY 795 = new MapMode("READ_ONLY"); 796 797 /** 798 * Mode for a read/write mapping. 799 */ 800 public static final MapMode READ_WRITE 801 = new MapMode("READ_WRITE"); 802 803 /** 804 * Mode for a private (copy-on-write) mapping. 805 */ 806 public static final MapMode PRIVATE 807 = new MapMode("PRIVATE"); 808 809 private final String name; 810 811 private MapMode(String name) { 812 this.name = name; 813 } 814 815 /** 816 * Returns a string describing this file-mapping mode. 817 * 818 * @return A descriptive string 819 */ 820 public String toString() { 821 return name; 822 } 823 824 } 825 826 /** 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 type=disc> 833 * 834 * <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer 835 * 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 will 839 * eventually be propagated to the file; they may or may not be made 840 * visible to other programs that have mapped the same file. ({@link 841 * MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li> 842 * 843 * <li><p> <i>Private:</i> Changes made to the resulting buffer will not 844 * be propagated to the file and will not be visible to other programs 845 * that have mapped the same file; instead, they will cause private 846 * copies of the modified portions of the buffer to be created. ({@link 847 * MapMode#PRIVATE MapMode.PRIVATE}) </p></li> 848 * 849 * </ul> 850 * 851 * <p> For a read-only mapping, this channel must have been opened for 852 * reading; for a read/write or private mapping, this channel must have 853 * 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 and 857 * capacity of <tt>size</tt>; its mark will be undefined. The buffer and 858 * the mapping that it represents will remain valid until the buffer itself 859 * is garbage-collected. 860 * 861 * <p> A mapping, once established, is not dependent upon the file channel 862 * that was used to create it. Closing the channel, in particular, has no 863 * effect upon the validity of the mapping. 864 * 865 * <p> Many of the details of memory-mapped files are inherently dependent 866 * upon the underlying operating system and are therefore unspecified. The 867 * behavior of this method when the requested region is not completely 868 * contained within this channel's file is unspecified. Whether changes 869 * made to the content or size of the underlying file, by this program or 870 * another, are propagated to the buffer is unspecified. The rate at which 871 * changes to the buffer are propagated to the file is unspecified. 872 * 873 * <p> For most operating systems, mapping a file into memory is more 874 * expensive than reading or writing a few tens of kilobytes of data via 875 * the usual {@link #read read} and {@link #write write} methods. From the 876 * standpoint of performance it is generally only worth mapping relatively 877 * large files into memory. </p> 878 * 879 * @param mode 880 * One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link 881 * MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE 882 * PRIVATE} defined in the {@link MapMode} class, according to 883 * whether the file is to be mapped read-only, read/write, or 884 * privately (copy-on-write), respectively 885 * 886 * @param position 887 * The position within the file at which the mapped region 888 * is to start; must be non-negative 889 * 890 * @param size 891 * The size of the region to be mapped; must be non-negative and 892 * no greater than {@link java.lang.Integer#MAX_VALUE} 893 * 894 * @return The mapped byte buffer 895 * 896 * @throws NonReadableChannelException 897 * If the <tt>mode</tt> is {@link MapMode#READ_ONLY READ_ONLY} but 898 * this channel was not opened for reading 899 * 900 * @throws NonWritableChannelException 901 * If the <tt>mode</tt> is {@link MapMode#READ_WRITE READ_WRITE} or 902 * {@link MapMode#PRIVATE PRIVATE} but this channel was not opened 903 * for both reading and writing 904 * 905 * @throws IllegalArgumentException 906 * If the preconditions on the parameters do not hold 907 * 908 * @throws IOException 909 * If some other I/O error occurs 910 * 911 * @see java.nio.channels.FileChannel.MapMode 912 * @see java.nio.MappedByteBuffer 913 */ 914 public abstract MappedByteBuffer map(MapMode mode, 915 long position, long size) 916 throws IOException; 917 918 919 // -- Locks -- 920 921 /** 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 be 925 * 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 of 929 * this method then an {@link AsynchronousCloseException} will be thrown. 930 * 931 * <p> If the invoking thread is interrupted while waiting to acquire the 932 * lock then its interrupt status will be set and a {@link 933 * FileLockInterruptionException} will be thrown. If the invoker's 934 * interrupt status is set when this method is invoked then that exception 935 * will be thrown immediately; the thread's interrupt status will not be 936 * 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 actual 940 * underlying file. Lock regions are fixed in size; if a locked region 941 * initially contains the end of the file and the file grows beyond the 942 * 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 is 944 * required then a region starting at zero, and no smaller than the 945 * expected maximum size of the file, should be locked. The zero-argument 946 * {@link #lock()} method simply locks a region of size {@link 947 * Long#MAX_VALUE}. 948 * 949 * <p> Some operating systems do not support shared locks, in which case a 950 * request for a shared lock is automatically converted into a request for 951 * an exclusive lock. Whether the newly-acquired lock is shared or 952 * exclusive may be tested by invoking the resulting lock object's {@link 953 * 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 multiple 957 * threads within the same virtual machine. </p> 958 * 959 * @param position 960 * The position at which the locked region is to start; must be 961 * non-negative 962 * 963 * @param size 964 * The size of the locked region; must be non-negative, and the sum 965 * <tt>position</tt> + <tt>size</tt> must be non-negative 966 * 967 * @param shared 968 * <tt>true</tt> to request a shared lock, in which case this 969 * channel must be open for reading (and possibly writing); 970 * <tt>false</tt> to request an exclusive lock, in which case this 971 * channel must be open for writing (and possibly reading) 972 * 973 * @return A lock object representing the newly-acquired lock 974 * 975 * @throws IllegalArgumentException 976 * If the preconditions on the parameters do not hold 977 * 978 * @throws ClosedChannelException 979 * If this channel is closed 980 * 981 * @throws AsynchronousCloseException 982 * If another thread closes this channel while the invoking 983 * thread is blocked in this method 984 * 985 * @throws FileLockInterruptionException 986 * If the invoking thread is interrupted while blocked in this 987 * method 988 * 989 * @throws OverlappingFileLockException 990 * If a lock that overlaps the requested region is already held by 991 * this Java virtual machine, or if another thread is already 992 * blocked in this method and is attempting to lock an overlapping 993 * region 994 * 995 * @throws NonReadableChannelException 996 * If <tt>shared</tt> is <tt>true</tt> this channel was not 997 * opened for reading 998 * 999 * @throws NonWritableChannelException 1000 * If <tt>shared</tt> is <tt>false</tt> but this channel was not 1001 * opened for writing 1002 * 1003 * @throws IOException 1004 * If some other I/O error occurs 1005 * 1006 * @see #lock() 1007 * @see #tryLock() 1008 * @see #tryLock(long,long,boolean) 1009 */ 1010 public abstract FileLock lock(long position, long size, boolean shared) 1011 throws IOException; 1012 1013 /** 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> behaves 1017 * in exactly the same way as the invocation 1018 * 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 lock 1023 * 1024 * @throws ClosedChannelException 1025 * If this channel is closed 1026 * 1027 * @throws AsynchronousCloseException 1028 * If another thread closes this channel while the invoking 1029 * thread is blocked in this method 1030 * 1031 * @throws FileLockInterruptionException 1032 * If the invoking thread is interrupted while blocked in this 1033 * method 1034 * 1035 * @throws OverlappingFileLockException 1036 * If a lock that overlaps the requested region is already held by 1037 * this Java virtual machine, or if another thread is already 1038 * blocked in this method and is attempting to lock an overlapping 1039 * region of the same file 1040 * 1041 * @throws NonWritableChannelException 1042 * If this channel was not opened for writing 1043 * 1044 * @throws IOException 1045 * If some other I/O error occurs 1046 * 1047 * @see #lock(long,long,boolean) 1048 * @see #tryLock() 1049 * @see #tryLock(long,long,boolean) 1050 */ 1051 public final FileLock lock() throws IOException { 1052 return lock(0L, Long.MAX_VALUE, false); 1053 } 1054 1055 /** 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 returns 1059 * immediately, either having acquired a lock on the requested region or 1060 * having failed to do so. If it fails to acquire a lock because an 1061 * overlapping lock is held by another program then it returns 1062 * <tt>null</tt>. If it fails to acquire a lock for any other reason then 1063 * 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 actual 1067 * underlying file. Lock regions are fixed in size; if a locked region 1068 * initially contains the end of the file and the file grows beyond the 1069 * 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 is 1071 * required then a region starting at zero, and no smaller than the 1072 * expected maximum size of the file, should be locked. The zero-argument 1073 * {@link #tryLock()} method simply locks a region of size {@link 1074 * Long#MAX_VALUE}. 1075 * 1076 * <p> Some operating systems do not support shared locks, in which case a 1077 * request for a shared lock is automatically converted into a request for 1078 * an exclusive lock. Whether the newly-acquired lock is shared or 1079 * exclusive may be tested by invoking the resulting lock object's {@link 1080 * 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 multiple 1084 * threads within the same virtual machine. </p> 1085 * 1086 * @param position 1087 * The position at which the locked region is to start; must be 1088 * non-negative 1089 * 1090 * @param size 1091 * The size of the locked region; must be non-negative, and the sum 1092 * <tt>position</tt> + <tt>size</tt> must be non-negative 1093 * 1094 * @param shared 1095 * <tt>true</tt> to request a shared lock, 1096 * <tt>false</tt> to request an exclusive lock 1097 * 1098 * @return A lock object representing the newly-acquired lock, 1099 * or <tt>null</tt> if the lock could not be acquired 1100 * because another program holds an overlapping lock 1101 * 1102 * @throws IllegalArgumentException 1103 * If the preconditions on the parameters do not hold 1104 * 1105 * @throws ClosedChannelException 1106 * If this channel is closed 1107 * 1108 * @throws OverlappingFileLockException 1109 * If a lock that overlaps the requested region is already held by 1110 * this Java virtual machine, or if another thread is already 1111 * blocked in this method and is attempting to lock an overlapping 1112 * region of the same file 1113 * 1114 * @throws IOException 1115 * If some other I/O error occurs 1116 * 1117 * @see #lock() 1118 * @see #lock(long,long,boolean) 1119 * @see #tryLock() 1120 */ 1121 public abstract FileLock tryLock(long position, long size, boolean shared) 1122 throws IOException; 1123 1124 /** 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 invocation 1129 * 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 acquired 1135 * because another program holds an overlapping lock 1136 * 1137 * @throws ClosedChannelException 1138 * If this channel is closed 1139 * 1140 * @throws OverlappingFileLockException 1141 * If a lock that overlaps the requested region is already held by 1142 * this Java virtual machine, or if another thread is already 1143 * blocked in this method and is attempting to lock an overlapping 1144 * region 1145 * 1146 * @throws IOException 1147 * If some other I/O error occurs 1148 * 1149 * @see #lock() 1150 * @see #lock(long,long,boolean) 1151 * @see #tryLock(long,long,boolean) 1152 */ 1153 public final FileLock tryLock() throws IOException { 1154 return tryLock(0L, Long.MAX_VALUE, false); 1155 } 1156 1157} 1158