1 /* 2 * Copyright (c) 2000, 2018, 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 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 <i>truncated</i>}. 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 {@code read} or {@code write} 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 {@code getChannel} 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 {@code getChannel} 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 id="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 {@code "r"} and will be open for reading and writing 132 * if the instance was created with mode {@code "rw"}. 133 * 134 * <a id="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 {@code true} 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 */ FileChannel()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 class="striped"> 178 * <caption style="display:none">additional options</caption> 179 * <thead> 180 * <tr> <th scope="col">Option</th> <th scope="col">Description</th> </tr> 181 * </thead> 182 * <tbody> 183 * <tr> 184 * <th scope="row"> {@link StandardOpenOption#APPEND APPEND} </th> 185 * <td> If this option is present then the file is opened for writing and 186 * each invocation of the channel's {@code write} method first advances 187 * the position to the end of the file and then writes the requested 188 * data. Whether the advancement of the position and the writing of the 189 * data are done in a single atomic operation is system-dependent and 190 * therefore unspecified. This option may not be used in conjunction 191 * with the {@code READ} or {@code TRUNCATE_EXISTING} options. </td> 192 * </tr> 193 * <tr> 194 * <th scope="row"> {@link StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} </th> 195 * <td> If this option is present then the existing file is truncated to 196 * a size of 0 bytes. This option is ignored when the file is opened only 197 * for reading. </td> 198 * </tr> 199 * <tr> 200 * <th scope="row"> {@link StandardOpenOption#CREATE_NEW CREATE_NEW} </th> 201 * <td> If this option is present then a new file is created, failing if 202 * the file already exists. When creating a file the check for the 203 * existence of the file and the creation of the file if it does not exist 204 * is atomic with respect to other file system operations. This option is 205 * ignored when the file is opened only for reading. </td> 206 * </tr> 207 * <tr> 208 * <th scope="row" > {@link StandardOpenOption#CREATE CREATE} </th> 209 * <td> If this option is present then an existing file is opened if it 210 * exists, otherwise a new file is created. When creating a file the check 211 * for the existence of the file and the creation of the file if it does 212 * not exist is atomic with respect to other file system operations. This 213 * option is ignored if the {@code CREATE_NEW} option is also present or 214 * the file is opened only for reading. </td> 215 * </tr> 216 * <tr> 217 * <th scope="row" > {@link StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE} </th> 218 * <td> When this option is present then the implementation makes a 219 * <em>best effort</em> attempt to delete the file when closed by 220 * the {@link #close close} method. If the {@code close} method is not 221 * invoked then a <em>best effort</em> attempt is made to delete the file 222 * when the Java virtual machine terminates. </td> 223 * </tr> 224 * <tr> 225 * <th scope="row">{@link StandardOpenOption#SPARSE SPARSE} </th> 226 * <td> When creating a new file this option is a <em>hint</em> that the 227 * new file will be sparse. This option is ignored when not creating 228 * a new file. </td> 229 * </tr> 230 * <tr> 231 * <th scope="row"> {@link StandardOpenOption#SYNC SYNC} </th> 232 * <td> Requires that every update to the file's content or metadata be 233 * written synchronously to the underlying storage device. (see <a 234 * href="../file/package-summary.html#integrity"> Synchronized I/O file 235 * integrity</a>). </td> 236 * </tr> 237 * <tr> 238 * <th scope="row"> {@link StandardOpenOption#DSYNC DSYNC} </th> 239 * <td> Requires that every update to the file's content be written 240 * synchronously to the underlying storage device. (see <a 241 * href="../file/package-summary.html#integrity"> Synchronized I/O file 242 * integrity</a>). </td> 243 * </tr> 244 * </tbody> 245 * </table> 246 * 247 * <p> An implementation may also support additional options. 248 * 249 * <p> The {@code attrs} parameter is an optional array of file {@link 250 * FileAttribute file-attributes} to set atomically when creating the file. 251 * 252 * <p> The new channel is created by invoking the {@link 253 * FileSystemProvider#newFileChannel newFileChannel} method on the 254 * provider that created the {@code Path}. 255 * 256 * @param path 257 * The path of the file to open or create 258 * @param options 259 * Options specifying how the file is opened 260 * @param attrs 261 * An optional list of file attributes to set atomically when 262 * creating the file 263 * 264 * @return A new file channel 265 * 266 * @throws IllegalArgumentException 267 * If the set contains an invalid combination of options 268 * @throws UnsupportedOperationException 269 * If the {@code path} is associated with a provider that does not 270 * support creating file channels, or an unsupported open option is 271 * specified, or the array contains an attribute that cannot be set 272 * atomically when creating the file 273 * @throws IOException 274 * If an I/O error occurs 275 * @throws SecurityException 276 * If a security manager is installed and it denies an 277 * unspecified permission required by the implementation. 278 * In the case of the default provider, the {@link 279 * SecurityManager#checkRead(String)} method is invoked to check 280 * read access if the file is opened for reading. The {@link 281 * SecurityManager#checkWrite(String)} method is invoked to check 282 * write access if the file is opened for writing 283 * 284 * @since 1.7 285 */ open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)286 public static FileChannel open(Path path, 287 Set<? extends OpenOption> options, 288 FileAttribute<?>... attrs) 289 throws IOException 290 { 291 FileSystemProvider provider = path.getFileSystem().provider(); 292 return provider.newFileChannel(path, options, attrs); 293 } 294 295 @SuppressWarnings({"unchecked", "rawtypes"}) // generic array construction 296 private static final FileAttribute<?>[] NO_ATTRIBUTES = new FileAttribute[0]; 297 298 /** 299 * Opens or creates a file, returning a file channel to access the file. 300 * 301 * <p> An invocation of this method behaves in exactly the same way as the 302 * invocation 303 * <pre> 304 * fc.{@link #open(Path,Set,FileAttribute[]) open}(file, opts, new FileAttribute<?>[0]); 305 * </pre> 306 * where {@code opts} is a set of the options specified in the {@code 307 * options} array. 308 * 309 * @param path 310 * The path of the file to open or create 311 * @param options 312 * Options specifying how the file is opened 313 * 314 * @return A new file channel 315 * 316 * @throws IllegalArgumentException 317 * If the set contains an invalid combination of options 318 * @throws UnsupportedOperationException 319 * If the {@code path} is associated with a provider that does not 320 * support creating file channels, or an unsupported open option is 321 * specified 322 * @throws IOException 323 * If an I/O error occurs 324 * @throws SecurityException 325 * If a security manager is installed and it denies an 326 * unspecified permission required by the implementation. 327 * In the case of the default provider, the {@link 328 * SecurityManager#checkRead(String)} method is invoked to check 329 * read access if the file is opened for reading. The {@link 330 * SecurityManager#checkWrite(String)} method is invoked to check 331 * write access if the file is opened for writing 332 * 333 * @since 1.7 334 */ open(Path path, OpenOption... options)335 public static FileChannel open(Path path, OpenOption... options) 336 throws IOException 337 { 338 Set<OpenOption> set; 339 if (options.length == 0) { 340 set = Collections.emptySet(); 341 } else { 342 set = new HashSet<>(); 343 Collections.addAll(set, options); 344 } 345 return open(path, set, NO_ATTRIBUTES); 346 } 347 348 // -- Channel operations -- 349 350 /** 351 * Reads a sequence of bytes from this channel into the given buffer. 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 * ReadableByteChannel} interface. </p> 357 */ read(ByteBuffer dst)358 public abstract int read(ByteBuffer dst) throws IOException; 359 360 /** 361 * Reads a sequence of bytes from this channel into a subsequence of the 362 * 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 */ read(ByteBuffer[] dsts, int offset, int length)369 public abstract long read(ByteBuffer[] dsts, int offset, int length) 370 throws IOException; 371 372 /** 373 * Reads a sequence of bytes from this channel into the given buffers. 374 * 375 * <p> Bytes are read starting at this channel's current file position, and 376 * then the file position is updated with the number of bytes actually 377 * read. Otherwise this method behaves exactly as specified in the {@link 378 * ScatteringByteChannel} interface. </p> 379 */ read(ByteBuffer[] dsts)380 public final long read(ByteBuffer[] dsts) throws IOException { 381 return read(dsts, 0, dsts.length); 382 } 383 384 /** 385 * Writes a sequence of bytes to this channel from the given buffer. 386 * 387 * <p> Bytes are written starting at this channel's current file position 388 * unless the channel is in append mode, in which case the position is 389 * first advanced to the end of the file. The file is grown, if necessary, 390 * to accommodate the written bytes, and then the file position is updated 391 * with the number of bytes actually written. Otherwise this method 392 * behaves exactly as specified by the {@link WritableByteChannel} 393 * interface. </p> 394 */ write(ByteBuffer src)395 public abstract int write(ByteBuffer src) throws IOException; 396 397 /** 398 * Writes a sequence of bytes to this channel from a subsequence of the 399 * given buffers. 400 * 401 * <p> Bytes are written starting at this channel's current file position 402 * unless the channel is in append mode, in which case the position is 403 * first advanced to the end of the file. The file is grown, if necessary, 404 * to accommodate the written bytes, and then the file position is updated 405 * with the number of bytes actually written. Otherwise this method 406 * behaves exactly as specified in the {@link GatheringByteChannel} 407 * interface. </p> 408 */ write(ByteBuffer[] srcs, int offset, int length)409 public abstract long write(ByteBuffer[] srcs, int offset, int length) 410 throws IOException; 411 412 /** 413 * Writes a sequence of bytes to this channel from the given buffers. 414 * 415 * <p> Bytes are written starting at this channel's current file position 416 * unless the channel is in append mode, in which case the position is 417 * first advanced to the end of the file. The file is grown, if necessary, 418 * to accommodate the written bytes, and then the file position is updated 419 * with the number of bytes actually written. Otherwise this method 420 * behaves exactly as specified in the {@link GatheringByteChannel} 421 * interface. </p> 422 */ write(ByteBuffer[] srcs)423 public final long write(ByteBuffer[] srcs) throws IOException { 424 return write(srcs, 0, srcs.length); 425 } 426 427 428 // -- Other operations -- 429 430 /** 431 * Returns this channel's file position. 432 * 433 * @return This channel's file position, 434 * a non-negative integer counting the number of bytes 435 * from the beginning of the file to the current position 436 * 437 * @throws ClosedChannelException 438 * If this channel is closed 439 * 440 * @throws IOException 441 * If some other I/O error occurs 442 */ position()443 public abstract long position() throws IOException; 444 445 /** 446 * Sets this channel's file position. 447 * 448 * <p> Setting the position to a value that is greater than the file's 449 * current size is legal but does not change the size of the file. A later 450 * attempt to read bytes at such a position will immediately return an 451 * end-of-file indication. A later attempt to write bytes at such a 452 * position will cause the file to be grown to accommodate the new bytes; 453 * the values of any bytes between the previous end-of-file and the 454 * newly-written bytes are unspecified. </p> 455 * 456 * @param newPosition 457 * The new position, a non-negative integer counting 458 * the number of bytes from the beginning of the file 459 * 460 * @return This file channel 461 * 462 * @throws ClosedChannelException 463 * If this channel is closed 464 * 465 * @throws IllegalArgumentException 466 * If the new position is negative 467 * 468 * @throws IOException 469 * If some other I/O error occurs 470 */ position(long newPosition)471 public abstract FileChannel position(long newPosition) throws IOException; 472 473 /** 474 * Returns the current size of this channel's file. 475 * 476 * @return The current size of this channel's file, 477 * measured in bytes 478 * 479 * @throws ClosedChannelException 480 * If this channel is closed 481 * 482 * @throws IOException 483 * If some other I/O error occurs 484 */ size()485 public abstract long size() throws IOException; 486 487 /** 488 * Truncates this channel's file to the given size. 489 * 490 * <p> If the given size is less than the file's current size then the file 491 * is truncated, discarding any bytes beyond the new end of the file. If 492 * the given size is greater than or equal to the file's current size then 493 * the file is not modified. In either case, if this channel's file 494 * position is greater than the given size then it is set to that size. 495 * </p> 496 * 497 * @param size 498 * The new size, a non-negative byte count 499 * 500 * @return This file channel 501 * 502 * @throws NonWritableChannelException 503 * If this channel was not opened for writing 504 * 505 * @throws ClosedChannelException 506 * If this channel is closed 507 * 508 * @throws IllegalArgumentException 509 * If the new size is negative 510 * 511 * @throws IOException 512 * If some other I/O error occurs 513 */ truncate(long size)514 public abstract FileChannel truncate(long size) throws IOException; 515 516 /** 517 * Forces any updates to this channel's file to be written to the storage 518 * device that contains it. 519 * 520 * <p> If this channel's file resides on a local storage device then when 521 * this method returns it is guaranteed that all changes made to the file 522 * since this channel was created, or since this method was last invoked, 523 * will have been written to that device. This is useful for ensuring that 524 * critical information is not lost in the event of a system crash. 525 * 526 * <p> If the file does not reside on a local device then no such guarantee 527 * is made. 528 * 529 * <p> The {@code metaData} parameter can be used to limit the number of 530 * I/O operations that this method is required to perform. Passing 531 * {@code false} for this parameter indicates that only updates to the 532 * file's content need be written to storage; passing {@code true} 533 * indicates that updates to both the file's content and metadata must be 534 * written, which generally requires at least one more I/O operation. 535 * Whether this parameter actually has any effect is dependent upon the 536 * underlying operating system and is therefore unspecified. 537 * 538 * <p> Invoking this method may cause an I/O operation to occur even if the 539 * channel was only opened for reading. Some operating systems, for 540 * example, maintain a last-access time as part of a file's metadata, and 541 * this time is updated whenever the file is read. Whether or not this is 542 * actually done is system-dependent and is therefore unspecified. 543 * 544 * <p> This method is only guaranteed to force changes that were made to 545 * this channel's file via the methods defined in this class. It may or 546 * may not force changes that were made by modifying the content of a 547 * {@link MappedByteBuffer <i>mapped byte buffer</i>} obtained by 548 * invoking the {@link #map map} method. Invoking the {@link 549 * MappedByteBuffer#force force} method of the mapped byte buffer will 550 * force changes made to the buffer's content to be written. </p> 551 * 552 * @param metaData 553 * If {@code true} then this method is required to force changes 554 * to both the file's content and metadata to be written to 555 * storage; otherwise, it need only force content changes to be 556 * written 557 * 558 * @throws ClosedChannelException 559 * If this channel is closed 560 * 561 * @throws IOException 562 * If some other I/O error occurs 563 */ force(boolean metaData)564 public abstract void force(boolean metaData) throws IOException; 565 566 /** 567 * Transfers bytes from this channel's file to the given writable byte 568 * channel. 569 * 570 * <p> An attempt is made to read up to {@code count} bytes starting at 571 * the given {@code position} in this channel's file and write them to the 572 * target channel. An invocation of this method may or may not transfer 573 * all of the requested bytes; whether or not it does so depends upon the 574 * natures and states of the channels. Fewer than the requested number of 575 * bytes are transferred if this channel's file contains fewer than 576 * {@code count} bytes starting at the given {@code position}, or if the 577 * target channel is non-blocking and it has fewer than {@code count} 578 * bytes free in its output buffer. 579 * 580 * <p> This method does not modify this channel's position. If the given 581 * position is greater than the file's current size then no bytes are 582 * transferred. If the target channel has a position then bytes are 583 * written starting at that position and then the position is incremented 584 * by the number of bytes written. 585 * 586 * <p> This method is potentially much more efficient than a simple loop 587 * that reads from this channel and writes to the target channel. Many 588 * operating systems can transfer bytes directly from the filesystem cache 589 * to the target channel without actually copying them. </p> 590 * 591 * @param position 592 * The position within the file at which the transfer is to begin; 593 * must be non-negative 594 * 595 * @param count 596 * The maximum number of bytes to be transferred; must be 597 * non-negative 598 * 599 * @param target 600 * The target channel 601 * 602 * @return The number of bytes, possibly zero, 603 * that were actually transferred 604 * 605 * @throws IllegalArgumentException 606 * If the preconditions on the parameters do not hold 607 * 608 * @throws NonReadableChannelException 609 * If this channel was not opened for reading 610 * 611 * @throws NonWritableChannelException 612 * If the target channel was not opened for writing 613 * 614 * @throws ClosedChannelException 615 * If either this channel or the target channel is closed 616 * 617 * @throws AsynchronousCloseException 618 * If another thread closes either channel 619 * while the transfer is in progress 620 * 621 * @throws ClosedByInterruptException 622 * If another thread interrupts the current thread while the 623 * transfer is in progress, thereby closing both channels and 624 * setting the current thread's interrupt status 625 * 626 * @throws IOException 627 * If some other I/O error occurs 628 */ transferTo(long position, long count, WritableByteChannel target)629 public abstract long transferTo(long position, long count, 630 WritableByteChannel target) 631 throws IOException; 632 633 /** 634 * Transfers bytes into this channel's file from the given readable byte 635 * channel. 636 * 637 * <p> An attempt is made to read up to {@code count} bytes from the 638 * source channel and write them to this channel's file starting at the 639 * given {@code position}. An invocation of this method may or may not 640 * transfer all of the requested bytes; whether or not it does so depends 641 * upon the natures and states of the channels. Fewer than the requested 642 * number of bytes will be transferred if the source channel has fewer than 643 * {@code count} bytes remaining, or if the source channel is non-blocking 644 * and has fewer than {@code count} bytes immediately available in its 645 * input buffer. 646 * 647 * <p> This method does not modify this channel's position. If the given 648 * position is greater than the file's current size then no bytes are 649 * transferred. If the source channel has a position then bytes are read 650 * starting at that position and then the position is incremented by the 651 * number of bytes read. 652 * 653 * <p> This method is potentially much more efficient than a simple loop 654 * that reads from the source channel and writes to this channel. Many 655 * operating systems can transfer bytes directly from the source channel 656 * into the filesystem cache without actually copying them. </p> 657 * 658 * @param src 659 * The source channel 660 * 661 * @param position 662 * The position within the file at which the transfer is to begin; 663 * must be non-negative 664 * 665 * @param count 666 * The maximum number of bytes to be transferred; must be 667 * non-negative 668 * 669 * @return The number of bytes, possibly zero, 670 * that were actually transferred 671 * 672 * @throws IllegalArgumentException 673 * If the preconditions on the parameters do not hold 674 * 675 * @throws NonReadableChannelException 676 * If the source channel was not opened for reading 677 * 678 * @throws NonWritableChannelException 679 * If this channel was not opened for writing 680 * 681 * @throws ClosedChannelException 682 * If either this channel or the source channel is closed 683 * 684 * @throws AsynchronousCloseException 685 * If another thread closes either channel 686 * while the transfer is in progress 687 * 688 * @throws ClosedByInterruptException 689 * If another thread interrupts the current thread while the 690 * transfer is in progress, thereby closing both channels and 691 * setting the current thread's interrupt status 692 * 693 * @throws IOException 694 * If some other I/O error occurs 695 */ transferFrom(ReadableByteChannel src, long position, long count)696 public abstract long transferFrom(ReadableByteChannel src, 697 long position, long count) 698 throws IOException; 699 700 /** 701 * Reads a sequence of bytes from this channel into the given buffer, 702 * starting at the given file position. 703 * 704 * <p> This method works in the same manner as the {@link 705 * #read(ByteBuffer)} method, except that bytes are read starting at the 706 * given file position rather than at the channel's current position. This 707 * method does not modify this channel's position. If the given position 708 * is greater than the file's current size then no bytes are read. </p> 709 * 710 * @param dst 711 * The buffer into which bytes are to be transferred 712 * 713 * @param position 714 * The file position at which the transfer is to begin; 715 * must be non-negative 716 * 717 * @return The number of bytes read, possibly zero, or {@code -1} if the 718 * given position is greater than or equal to the file's current 719 * size 720 * 721 * @throws IllegalArgumentException 722 * If the position is negative 723 * 724 * @throws NonReadableChannelException 725 * If this channel was not opened for reading 726 * 727 * @throws ClosedChannelException 728 * If this channel is closed 729 * 730 * @throws AsynchronousCloseException 731 * If another thread closes this channel 732 * while the read operation is in progress 733 * 734 * @throws ClosedByInterruptException 735 * If another thread interrupts the current thread 736 * while the read operation is in progress, thereby 737 * closing the channel and setting the current thread's 738 * interrupt status 739 * 740 * @throws IOException 741 * If some other I/O error occurs 742 */ read(ByteBuffer dst, long position)743 public abstract int read(ByteBuffer dst, long position) throws IOException; 744 745 /** 746 * Writes a sequence of bytes to this channel from the given buffer, 747 * starting at the given file position. 748 * 749 * <p> This method works in the same manner as the {@link 750 * #write(ByteBuffer)} method, except that bytes are written starting at 751 * the given file position rather than at the channel's current position. 752 * This method does not modify this channel's position. If the given 753 * position is greater than the file's current size then the file will be 754 * grown to accommodate the new bytes; the values of any bytes between the 755 * previous end-of-file and the newly-written bytes are unspecified. </p> 756 * 757 * @param src 758 * The buffer from which bytes are to be transferred 759 * 760 * @param position 761 * The file position at which the transfer is to begin; 762 * must be non-negative 763 * 764 * @return The number of bytes written, possibly zero 765 * 766 * @throws IllegalArgumentException 767 * If the position is negative 768 * 769 * @throws NonWritableChannelException 770 * If this channel was not opened for writing 771 * 772 * @throws ClosedChannelException 773 * If this channel is closed 774 * 775 * @throws AsynchronousCloseException 776 * If another thread closes this channel 777 * while the write operation is in progress 778 * 779 * @throws ClosedByInterruptException 780 * If another thread interrupts the current thread 781 * while the write operation is in progress, thereby 782 * closing the channel and setting the current thread's 783 * interrupt status 784 * 785 * @throws IOException 786 * If some other I/O error occurs 787 */ write(ByteBuffer src, long position)788 public abstract int write(ByteBuffer src, long position) throws IOException; 789 790 791 // -- Memory-mapped buffers -- 792 793 /** 794 * A typesafe enumeration for file-mapping modes. 795 * 796 * @since 1.4 797 * 798 * @see java.nio.channels.FileChannel#map 799 */ 800 public static class MapMode { 801 802 /** 803 * Mode for a read-only mapping. 804 */ 805 public static final MapMode READ_ONLY 806 = new MapMode("READ_ONLY"); 807 808 /** 809 * Mode for a read/write mapping. 810 */ 811 public static final MapMode READ_WRITE 812 = new MapMode("READ_WRITE"); 813 814 /** 815 * Mode for a private (copy-on-write) mapping. 816 */ 817 public static final MapMode PRIVATE 818 = new MapMode("PRIVATE"); 819 820 private final String name; 821 MapMode(String name)822 private MapMode(String name) { 823 this.name = name; 824 } 825 826 /** 827 * Returns a string describing this file-mapping mode. 828 * 829 * @return A descriptive string 830 */ toString()831 public String toString() { 832 return name; 833 } 834 835 } 836 837 /** 838 * Maps a region of this channel's file directly into memory. 839 * 840 * <p> A region of a file may be mapped into memory in one of three modes: 841 * </p> 842 * 843 * <ul> 844 * 845 * <li><p> <i>Read-only:</i> Any attempt to modify the resulting buffer 846 * will cause a {@link java.nio.ReadOnlyBufferException} to be thrown. 847 * ({@link MapMode#READ_ONLY MapMode.READ_ONLY}) </p></li> 848 * 849 * <li><p> <i>Read/write:</i> Changes made to the resulting buffer will 850 * eventually be propagated to the file; they may or may not be made 851 * visible to other programs that have mapped the same file. ({@link 852 * MapMode#READ_WRITE MapMode.READ_WRITE}) </p></li> 853 * 854 * <li><p> <i>Private:</i> Changes made to the resulting buffer will not 855 * be propagated to the file and will not be visible to other programs 856 * that have mapped the same file; instead, they will cause private 857 * copies of the modified portions of the buffer to be created. ({@link 858 * MapMode#PRIVATE MapMode.PRIVATE}) </p></li> 859 * 860 * </ul> 861 * 862 * <p> For a read-only mapping, this channel must have been opened for 863 * reading; for a read/write or private mapping, this channel must have 864 * been opened for both reading and writing. 865 * 866 * <p> The {@link MappedByteBuffer <i>mapped byte buffer</i>} 867 * returned by this method will have a position of zero and a limit and 868 * capacity of {@code size}; its mark will be undefined. The buffer and 869 * the mapping that it represents will remain valid until the buffer itself 870 * is garbage-collected. 871 * 872 * <p> A mapping, once established, is not dependent upon the file channel 873 * that was used to create it. Closing the channel, in particular, has no 874 * effect upon the validity of the mapping. 875 * 876 * <p> Many of the details of memory-mapped files are inherently dependent 877 * upon the underlying operating system and are therefore unspecified. The 878 * behavior of this method when the requested region is not completely 879 * contained within this channel's file is unspecified. Whether changes 880 * made to the content or size of the underlying file, by this program or 881 * another, are propagated to the buffer is unspecified. The rate at which 882 * changes to the buffer are propagated to the file is unspecified. 883 * 884 * <p> For most operating systems, mapping a file into memory is more 885 * expensive than reading or writing a few tens of kilobytes of data via 886 * the usual {@link #read read} and {@link #write write} methods. From the 887 * standpoint of performance it is generally only worth mapping relatively 888 * large files into memory. </p> 889 * 890 * @param mode 891 * One of the constants {@link MapMode#READ_ONLY READ_ONLY}, {@link 892 * MapMode#READ_WRITE READ_WRITE}, or {@link MapMode#PRIVATE 893 * PRIVATE} defined in the {@link MapMode} class, according to 894 * whether the file is to be mapped read-only, read/write, or 895 * privately (copy-on-write), respectively 896 * 897 * @param position 898 * The position within the file at which the mapped region 899 * is to start; must be non-negative 900 * 901 * @param size 902 * The size of the region to be mapped; must be non-negative and 903 * no greater than {@link java.lang.Integer#MAX_VALUE} 904 * 905 * @return The mapped byte buffer 906 * 907 * @throws NonReadableChannelException 908 * If the {@code mode} is {@link MapMode#READ_ONLY READ_ONLY} but 909 * this channel was not opened for reading 910 * 911 * @throws NonWritableChannelException 912 * If the {@code mode} is {@link MapMode#READ_WRITE READ_WRITE} or 913 * {@link MapMode#PRIVATE PRIVATE} but this channel was not opened 914 * for both reading and writing 915 * 916 * @throws IllegalArgumentException 917 * If the preconditions on the parameters do not hold 918 * 919 * @throws IOException 920 * If some other I/O error occurs 921 * 922 * @see java.nio.channels.FileChannel.MapMode 923 * @see java.nio.MappedByteBuffer 924 */ map(MapMode mode, long position, long size)925 public abstract MappedByteBuffer map(MapMode mode, 926 long position, long size) 927 throws IOException; 928 929 930 // -- Locks -- 931 932 /** 933 * Acquires a lock on the given region of this channel's file. 934 * 935 * <p> An invocation of this method will block until the region can be 936 * locked, this channel is closed, or the invoking thread is interrupted, 937 * whichever comes first. 938 * 939 * <p> If this channel is closed by another thread during an invocation of 940 * this method then an {@link AsynchronousCloseException} will be thrown. 941 * 942 * <p> If the invoking thread is interrupted while waiting to acquire the 943 * lock then its interrupt status will be set and a {@link 944 * FileLockInterruptionException} will be thrown. If the invoker's 945 * interrupt status is set when this method is invoked then that exception 946 * will be thrown immediately; the thread's interrupt status will not be 947 * changed. 948 * 949 * <p> The region specified by the {@code position} and {@code size} 950 * parameters need not be contained within, or even overlap, the actual 951 * underlying file. Lock regions are fixed in size; if a locked region 952 * initially contains the end of the file and the file grows beyond the 953 * region then the new portion of the file will not be covered by the lock. 954 * If a file is expected to grow in size and a lock on the entire file is 955 * required then a region starting at zero, and no smaller than the 956 * expected maximum size of the file, should be locked. The zero-argument 957 * {@link #lock()} method simply locks a region of size {@link 958 * Long#MAX_VALUE}. 959 * 960 * <p> Some operating systems do not support shared locks, in which case a 961 * request for a shared lock is automatically converted into a request for 962 * an exclusive lock. Whether the newly-acquired lock is shared or 963 * exclusive may be tested by invoking the resulting lock object's {@link 964 * FileLock#isShared() isShared} method. 965 * 966 * <p> File locks are held on behalf of the entire Java virtual machine. 967 * They are not suitable for controlling access to a file by multiple 968 * threads within the same virtual machine. </p> 969 * 970 * @param position 971 * The position at which the locked region is to start; must be 972 * non-negative 973 * 974 * @param size 975 * The size of the locked region; must be non-negative, and the sum 976 * {@code position} + {@code size} must be non-negative 977 * 978 * @param shared 979 * {@code true} to request a shared lock, in which case this 980 * channel must be open for reading (and possibly writing); 981 * {@code false} to request an exclusive lock, in which case this 982 * channel must be open for writing (and possibly reading) 983 * 984 * @return A lock object representing the newly-acquired lock 985 * 986 * @throws IllegalArgumentException 987 * If the preconditions on the parameters do not hold 988 * 989 * @throws ClosedChannelException 990 * If this channel is closed 991 * 992 * @throws AsynchronousCloseException 993 * If another thread closes this channel while the invoking 994 * thread is blocked in this method 995 * 996 * @throws FileLockInterruptionException 997 * If the invoking thread is interrupted while blocked in this 998 * method 999 * 1000 * @throws OverlappingFileLockException 1001 * If a lock that overlaps the requested region is already held by 1002 * this Java virtual machine, or if another thread is already 1003 * blocked in this method and is attempting to lock an overlapping 1004 * region 1005 * 1006 * @throws NonReadableChannelException 1007 * If {@code shared} is {@code true} this channel was not 1008 * opened for reading 1009 * 1010 * @throws NonWritableChannelException 1011 * If {@code shared} is {@code false} but this channel was not 1012 * opened for writing 1013 * 1014 * @throws IOException 1015 * If some other I/O error occurs 1016 * 1017 * @see #lock() 1018 * @see #tryLock() 1019 * @see #tryLock(long,long,boolean) 1020 */ lock(long position, long size, boolean shared)1021 public abstract FileLock lock(long position, long size, boolean shared) 1022 throws IOException; 1023 1024 /** 1025 * Acquires an exclusive lock on this channel's file. 1026 * 1027 * <p> An invocation of this method of the form {@code fc.lock()} behaves 1028 * in exactly the same way as the invocation 1029 * 1030 * <pre> 1031 * fc.{@link #lock(long,long,boolean) lock}(0L, Long.MAX_VALUE, false) </pre> 1032 * 1033 * @return A lock object representing the newly-acquired lock 1034 * 1035 * @throws ClosedChannelException 1036 * If this channel is closed 1037 * 1038 * @throws AsynchronousCloseException 1039 * If another thread closes this channel while the invoking 1040 * thread is blocked in this method 1041 * 1042 * @throws FileLockInterruptionException 1043 * If the invoking thread is interrupted while blocked in this 1044 * method 1045 * 1046 * @throws OverlappingFileLockException 1047 * If a lock that overlaps the requested region is already held by 1048 * this Java virtual machine, or if another thread is already 1049 * blocked in this method and is attempting to lock an overlapping 1050 * region of the same file 1051 * 1052 * @throws NonWritableChannelException 1053 * If this channel was not opened for writing 1054 * 1055 * @throws IOException 1056 * If some other I/O error occurs 1057 * 1058 * @see #lock(long,long,boolean) 1059 * @see #tryLock() 1060 * @see #tryLock(long,long,boolean) 1061 */ lock()1062 public final FileLock lock() throws IOException { 1063 return lock(0L, Long.MAX_VALUE, false); 1064 } 1065 1066 /** 1067 * Attempts to acquire a lock on the given region of this channel's file. 1068 * 1069 * <p> This method does not block. An invocation always returns 1070 * immediately, either having acquired a lock on the requested region or 1071 * having failed to do so. If it fails to acquire a lock because an 1072 * overlapping lock is held by another program then it returns 1073 * {@code null}. If it fails to acquire a lock for any other reason then 1074 * an appropriate exception is thrown. 1075 * 1076 * <p> The region specified by the {@code position} and {@code size} 1077 * parameters need not be contained within, or even overlap, the actual 1078 * underlying file. Lock regions are fixed in size; if a locked region 1079 * initially contains the end of the file and the file grows beyond the 1080 * region then the new portion of the file will not be covered by the lock. 1081 * If a file is expected to grow in size and a lock on the entire file is 1082 * required then a region starting at zero, and no smaller than the 1083 * expected maximum size of the file, should be locked. The zero-argument 1084 * {@link #tryLock()} method simply locks a region of size {@link 1085 * Long#MAX_VALUE}. 1086 * 1087 * <p> Some operating systems do not support shared locks, in which case a 1088 * request for a shared lock is automatically converted into a request for 1089 * an exclusive lock. Whether the newly-acquired lock is shared or 1090 * exclusive may be tested by invoking the resulting lock object's {@link 1091 * FileLock#isShared() isShared} method. 1092 * 1093 * <p> File locks are held on behalf of the entire Java virtual machine. 1094 * They are not suitable for controlling access to a file by multiple 1095 * threads within the same virtual machine. </p> 1096 * 1097 * @param position 1098 * The position at which the locked region is to start; must be 1099 * non-negative 1100 * 1101 * @param size 1102 * The size of the locked region; must be non-negative, and the sum 1103 * {@code position} + {@code size} must be non-negative 1104 * 1105 * @param shared 1106 * {@code true} to request a shared lock, 1107 * {@code false} to request an exclusive lock 1108 * 1109 * @return A lock object representing the newly-acquired lock, 1110 * or {@code null} if the lock could not be acquired 1111 * because another program holds an overlapping lock 1112 * 1113 * @throws IllegalArgumentException 1114 * If the preconditions on the parameters do not hold 1115 * 1116 * @throws ClosedChannelException 1117 * If this channel is closed 1118 * 1119 * @throws OverlappingFileLockException 1120 * If a lock that overlaps the requested region is already held by 1121 * this Java virtual machine, or if another thread is already 1122 * blocked in this method and is attempting to lock an overlapping 1123 * region of the same file 1124 * 1125 * @throws IOException 1126 * If some other I/O error occurs 1127 * 1128 * @see #lock() 1129 * @see #lock(long,long,boolean) 1130 * @see #tryLock() 1131 */ tryLock(long position, long size, boolean shared)1132 public abstract FileLock tryLock(long position, long size, boolean shared) 1133 throws IOException; 1134 1135 /** 1136 * Attempts to acquire an exclusive lock on this channel's file. 1137 * 1138 * <p> An invocation of this method of the form {@code fc.tryLock()} 1139 * behaves in exactly the same way as the invocation 1140 * 1141 * <pre> 1142 * fc.{@link #tryLock(long,long,boolean) tryLock}(0L, Long.MAX_VALUE, false) </pre> 1143 * 1144 * @return A lock object representing the newly-acquired lock, 1145 * or {@code null} if the lock could not be acquired 1146 * because another program holds an overlapping lock 1147 * 1148 * @throws ClosedChannelException 1149 * If this channel is closed 1150 * 1151 * @throws OverlappingFileLockException 1152 * If a lock that overlaps the requested region is already held by 1153 * this Java virtual machine, or if another thread is already 1154 * blocked in this method and is attempting to lock an overlapping 1155 * region 1156 * 1157 * @throws IOException 1158 * If some other I/O error occurs 1159 * 1160 * @see #lock() 1161 * @see #lock(long,long,boolean) 1162 * @see #tryLock(long,long,boolean) 1163 */ tryLock()1164 public final FileLock tryLock() throws IOException { 1165 return tryLock(0L, Long.MAX_VALUE, false); 1166 } 1167 1168 } 1169