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