1 /* 2 * Copyright (c) 1994, 2024, 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.io; 27 28 import java.nio.channels.FileChannel; 29 30 import jdk.internal.access.JavaIORandomAccessFileAccess; 31 import jdk.internal.access.SharedSecrets; 32 import jdk.internal.misc.Blocker; 33 import jdk.internal.util.ByteArray; 34 import sun.nio.ch.FileChannelImpl; 35 36 37 /** 38 * Instances of this class support both reading and writing to a 39 * random access file. A random access file behaves like a large 40 * array of bytes stored in the file system. There is a kind of cursor, 41 * or index into the implied array, called the <em>file pointer</em>; 42 * input operations read bytes starting at the file pointer and advance 43 * the file pointer past the bytes read. If the random access file is 44 * created in read/write mode, then output operations are also available; 45 * output operations write bytes starting at the file pointer and advance 46 * the file pointer past the bytes written. Output operations that write 47 * past the current end of the implied array cause the array to be 48 * extended. The file pointer can be read by the 49 * {@code getFilePointer} method and set by the {@code seek} 50 * method. 51 * <p> 52 * It is generally true of all the reading routines in this class that 53 * if end-of-file is reached before the desired number of bytes has been 54 * read, an {@code EOFException} (which is a kind of 55 * {@code IOException}) is thrown. If any byte cannot be read for 56 * any reason other than end-of-file, an {@code IOException} other 57 * than {@code EOFException} is thrown. In particular, an 58 * {@code IOException} may be thrown if the stream has been closed. 59 * 60 * @since 1.0 61 */ 62 63 public class RandomAccessFile implements DataOutput, DataInput, Closeable { 64 65 private static final int O_RDONLY = 1; 66 private static final int O_RDWR = 2; 67 private static final int O_SYNC = 4; 68 private static final int O_DSYNC = 8; 69 private static final int O_TEMPORARY = 16; 70 71 private final FileDescriptor fd; 72 73 private final boolean rw; 74 75 /** 76 * The path of the referenced file 77 * (null if the stream is created with a file descriptor) 78 */ 79 private final String path; 80 81 private final Object closeLock = new Object(); 82 83 /** 84 * A local buffer that allows reading and writing of 85 * longer primitive parameters (e.g. long) to be performed 86 * using bulk operations rather than on a per-byte basis. 87 */ 88 private final byte[] buffer = new byte[Long.BYTES]; 89 90 private volatile FileChannel channel; 91 private volatile boolean closed; 92 93 /** 94 * Creates a random access file stream to read from, and optionally 95 * to write to, a file with the specified pathname. A new 96 * {@link FileDescriptor} object is created to represent the 97 * connection to the file. 98 * 99 * <p> The {@code mode} argument specifies the access mode with which the 100 * file is to be opened. The permitted values and their meanings are as 101 * specified for the <a 102 * href="#mode">{@code RandomAccessFile(File,String)}</a> constructor. 103 * 104 * <p> 105 * If there is a security manager, its {@code checkRead} method 106 * is called with the {@code pathname} argument 107 * as its argument to see if read access to the file is allowed. 108 * If the mode allows writing, the security manager's 109 * {@code checkWrite} method 110 * is also called with the {@code pathname} argument 111 * as its argument to see if write access to the file is allowed. 112 * 113 * @param pathname the system-dependent pathname string 114 * @param mode the access <a href="#mode">mode</a> 115 * @throws IllegalArgumentException if the mode argument is not equal 116 * to one of {@code "r"}, {@code "rw"}, {@code "rws"}, or 117 * {@code "rwd"} 118 * @throws FileNotFoundException 119 * if the mode is {@code "r"} but the given pathname string does not 120 * denote an existing regular file, or if the mode begins with 121 * {@code "rw"} but the given pathname string does not denote an 122 * existing, writable regular file and a new regular file of 123 * that pathname cannot be created, or if some other error 124 * occurs while opening or creating the file 125 * @throws SecurityException if a security manager exists and its 126 * {@code checkRead} method denies read access to the file 127 * or the mode is {@code "rw"} and the security manager's 128 * {@code checkWrite} method denies write access to the file 129 * @see java.lang.SecurityException 130 * @see java.lang.SecurityManager#checkRead(java.lang.String) 131 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 132 */ 133 public RandomAccessFile(String pathname, String mode) 134 throws FileNotFoundException 135 { 136 this(pathname != null ? new File(pathname) : null, mode); 137 } 138 139 /** 140 * Creates a random access file stream to read from, and optionally to 141 * write to, the file specified by the {@link File} argument. A new {@link 142 * FileDescriptor} object is created to represent this file connection. 143 * 144 * <p>The <a id="mode">{@code mode}</a> argument specifies the access mode 145 * in which the file is to be opened. The permitted values and their 146 * meanings are: 147 * 148 * <table class="striped"> 149 * <caption style="display:none">Access mode permitted values and meanings</caption> 150 * <thead> 151 * <tr><th scope="col" style="text-align:left">Value</th><th scope="col" style="text-align:left">Meaning</th></tr> 152 * </thead> 153 * <tbody> 154 * <tr><th scope="row" style="vertical-align:top">{@code "r"}</th> 155 * <td> Open for reading only. Invoking any of the {@code write} 156 * methods of the resulting object will cause an 157 * {@link java.io.IOException} to be thrown.</td></tr> 158 * <tr><th scope="row" style="vertical-align:top">{@code "rw"}</th> 159 * <td> Open for reading and writing. If the file does not already 160 * exist then an attempt will be made to create it.</td></tr> 161 * <tr><th scope="row" style="vertical-align:top">{@code "rws"}</th> 162 * <td> Open for reading and writing, as with {@code "rw"}, and also 163 * require that every update to the file's content or metadata be 164 * written synchronously to the underlying storage device.</td></tr> 165 * <tr><th scope="row" style="vertical-align:top">{@code "rwd"}</th> 166 * <td> Open for reading and writing, as with {@code "rw"}, and also 167 * require that every update to the file's content be written 168 * synchronously to the underlying storage device.</td></tr> 169 * </tbody> 170 * </table> 171 * 172 * The {@code "rws"} and {@code "rwd"} modes work much like the {@link 173 * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of 174 * the {@link java.nio.channels.FileChannel} class, passing arguments of 175 * {@code true} and {@code false}, respectively, except that they always 176 * apply to every I/O operation and are therefore often more efficient. If 177 * the file resides on a local storage device then when an invocation of a 178 * method of this class returns it is guaranteed that all changes made to 179 * the file by that invocation will have been written to that device. This 180 * is useful for ensuring that critical information is not lost in the 181 * event of a system crash. If the file does not reside on a local device 182 * then no such guarantee is made. 183 * 184 * <p>The {@code "rwd"} mode can be used to reduce the number of I/O 185 * operations performed. Using {@code "rwd"} only requires updates to the 186 * file's content to be written to storage; using {@code "rws"} requires 187 * updates to both the file's content and its metadata to be written, which 188 * generally requires at least one more low-level I/O operation. 189 * 190 * <p>If there is a security manager, its {@code checkRead} method is 191 * called with the pathname of the {@code file} argument as its 192 * argument to see if read access to the file is allowed. If the mode 193 * allows writing, the security manager's {@code checkWrite} method is 194 * also called with the pathname of the {@code file} argument to see if 195 * write access to the file is allowed. 196 * 197 * @param file the file object 198 * @param mode the access mode, as described 199 * <a href="#mode">above</a> 200 * @throws IllegalArgumentException if the mode argument is not equal 201 * to one of {@code "r"}, {@code "rw"}, {@code "rws"}, or 202 * {@code "rwd"} 203 * @throws FileNotFoundException 204 * if the mode is {@code "r"} but the given file object does 205 * not denote an existing regular file, or if the mode begins 206 * with {@code "rw"} but the given file object does not denote 207 * an existing, writable regular file and a new regular file of 208 * that pathname cannot be created, or if some other error 209 * occurs while opening or creating the file 210 * @throws SecurityException if a security manager exists and its 211 * {@code checkRead} method denies read access to the file 212 * or the mode is {@code "rw"} and the security manager's 213 * {@code checkWrite} method denies write access to the file 214 * @see java.lang.SecurityManager#checkRead(java.lang.String) 215 * @see java.lang.SecurityManager#checkWrite(java.lang.String) 216 * @see java.nio.channels.FileChannel#force(boolean) 217 */ 218 @SuppressWarnings("this-escape") 219 public RandomAccessFile(File file, String mode) 220 throws FileNotFoundException 221 { 222 this(file, mode, false); 223 } 224 225 private RandomAccessFile(File file, String mode, boolean openAndDelete) 226 throws FileNotFoundException 227 { 228 String name = (file != null ? file.getPath() : null); 229 int imode = -1; 230 231 boolean rw = false; 232 if (mode.equals("r")) 233 imode = O_RDONLY; 234 else if (mode.startsWith("rw")) { 235 imode = O_RDWR; 236 rw = true; 237 if (mode.length() > 2) { 238 if (mode.equals("rws")) 239 imode |= O_SYNC; 240 else if (mode.equals("rwd")) 241 imode |= O_DSYNC; 242 else 243 imode = -1; 244 } 245 } 246 this.rw = rw; 247 248 if (openAndDelete) 249 imode |= O_TEMPORARY; 250 if (imode < 0) 251 throw new IllegalArgumentException("Illegal mode \"" + mode 252 + "\" must be one of " 253 + "\"r\", \"rw\", \"rws\"," 254 + " or \"rwd\""); 255 @SuppressWarnings("removal") 256 SecurityManager security = System.getSecurityManager(); 257 if (security != null) { 258 security.checkRead(name); 259 if (rw) { 260 security.checkWrite(name); 261 } 262 } 263 if (name == null) { 264 throw new NullPointerException(); 265 } 266 if (file.isInvalid()) { 267 throw new FileNotFoundException("Invalid file path"); 268 } 269 fd = new FileDescriptor(); 270 fd.attach(this); 271 path = name; 272 open(name, imode); 273 FileCleanable.register(fd); // open sets the fd, register the cleanup 274 } 275 276 /** 277 * Returns the opaque file descriptor object associated with this 278 * stream. 279 * 280 * @return the file descriptor object associated with this stream. 281 * @throws IOException if an I/O error occurs. 282 * @see java.io.FileDescriptor 283 */ 284 public final FileDescriptor getFD() throws IOException { 285 return fd; 286 } 287 288 /** 289 * Returns the unique {@link java.nio.channels.FileChannel FileChannel} 290 * object associated with this file. 291 * 292 * <p> The {@link java.nio.channels.FileChannel#position() 293 * position} of the returned channel will always be equal to 294 * this object's file-pointer offset as returned by the {@link 295 * #getFilePointer getFilePointer} method. Changing this object's 296 * file-pointer offset, whether explicitly or by reading or writing bytes, 297 * will change the position of the channel, and vice versa. Changing the 298 * file's length via this object will change the length seen via the file 299 * channel, and vice versa. 300 * 301 * @return the file channel associated with this file 302 * 303 * @since 1.4 304 */ 305 public final FileChannel getChannel() { 306 FileChannel fc = this.channel; 307 if (fc == null) { 308 synchronized (this) { 309 fc = this.channel; 310 if (fc == null) { 311 this.channel = fc = FileChannelImpl.open(fd, path, true, 312 rw, false, this); 313 if (closed) { 314 try { 315 fc.close(); 316 } catch (IOException ioe) { 317 throw new InternalError(ioe); // should not happen 318 } 319 } 320 } 321 } 322 } 323 return fc; 324 } 325 326 /** 327 * Opens a file and returns the file descriptor. The file is 328 * opened in read-write mode if the O_RDWR bit in {@code mode} 329 * is true, else the file is opened as read-only. 330 * If the {@code name} refers to a directory, an IOException 331 * is thrown. 332 * 333 * @param name the name of the file 334 * @param mode the mode flags, a combination of the O_ constants 335 * defined above 336 */ 337 private native void open0(String name, int mode) 338 throws FileNotFoundException; 339 340 // wrap native call to allow instrumentation 341 /** 342 * Opens a file and returns the file descriptor. The file is 343 * opened in read-write mode if the O_RDWR bit in {@code mode} 344 * is true, else the file is opened as read-only. 345 * If the {@code name} refers to a directory, an IOException 346 * is thrown. 347 * 348 * @param name the name of the file 349 * @param mode the mode flags, a combination of the O_ constants 350 * defined above 351 */ 352 private void open(String name, int mode) throws FileNotFoundException { 353 long comp = Blocker.begin(); 354 try { 355 open0(name, mode); 356 } finally { 357 Blocker.end(comp); 358 } 359 } 360 361 // 'Read' primitives 362 363 /** 364 * Reads a byte of data from this file. The byte is returned as an 365 * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This 366 * method blocks if no input is yet available. 367 * <p> 368 * Although {@code RandomAccessFile} is not a subclass of 369 * {@code InputStream}, this method behaves in exactly the same 370 * way as the {@link InputStream#read()} method of 371 * {@code InputStream}. 372 * 373 * @return the next byte of data, or {@code -1} if the end of the 374 * file has been reached. 375 * @throws IOException if an I/O error occurs. Not thrown if 376 * end-of-file has been reached. 377 */ 378 public int read() throws IOException { 379 long comp = Blocker.begin(); 380 try { 381 return read0(); 382 } finally { 383 Blocker.end(comp); 384 } 385 } 386 387 private native int read0() throws IOException; 388 389 /** 390 * Reads a sub array as a sequence of bytes. 391 * @param b the buffer into which the data is read. 392 * @param off the start offset of the data. 393 * @param len the number of bytes to read. 394 * @throws IOException If an I/O error has occurred. 395 */ 396 private int readBytes(byte[] b, int off, int len) throws IOException { 397 long comp = Blocker.begin(); 398 try { 399 return readBytes0(b, off, len); 400 } finally { 401 Blocker.end(comp); 402 } 403 } 404 405 private native int readBytes0(byte[] b, int off, int len) throws IOException; 406 407 /** 408 * Reads up to {@code len} bytes of data from this file into an 409 * array of bytes. This method blocks until at least one byte of input 410 * is available. 411 * <p> 412 * Although {@code RandomAccessFile} is not a subclass of 413 * {@code InputStream}, this method behaves in exactly the 414 * same way as the {@link InputStream#read(byte[], int, int)} method of 415 * {@code InputStream}. 416 * 417 * @param b the buffer into which the data is read. 418 * @param off the start offset in array {@code b} 419 * at which the data is written. 420 * @param len the maximum number of bytes read. 421 * @return the total number of bytes read into the buffer, or 422 * {@code -1} if there is no more data because the end of 423 * the file has been reached. 424 * @throws IOException If the first byte cannot be read for any reason 425 * other than end of file, or if the random access file has been closed, 426 * or if some other I/O error occurs. 427 * @throws NullPointerException If {@code b} is {@code null}. 428 * @throws IndexOutOfBoundsException If {@code off} is negative, 429 * {@code len} is negative, or {@code len} is greater than 430 * {@code b.length - off} 431 */ 432 public int read(byte[] b, int off, int len) throws IOException { 433 return readBytes(b, off, len); 434 } 435 436 /** 437 * Reads up to {@code b.length} bytes of data from this file 438 * into an array of bytes. This method blocks until at least one byte 439 * of input is available. 440 * <p> 441 * Although {@code RandomAccessFile} is not a subclass of 442 * {@code InputStream}, this method behaves in exactly the 443 * same way as the {@link InputStream#read(byte[])} method of 444 * {@code InputStream}. 445 * 446 * @param b the buffer into which the data is read. 447 * @return the total number of bytes read into the buffer, or 448 * {@code -1} if there is no more data because the end of 449 * this file has been reached. 450 * @throws IOException If the first byte cannot be read for any reason 451 * other than end of file, or if the random access file has been closed, 452 * or if some other I/O error occurs. 453 * @throws NullPointerException If {@code b} is {@code null}. 454 */ 455 public int read(byte[] b) throws IOException { 456 return readBytes(b, 0, b.length); 457 } 458 459 /** 460 * Reads {@code b.length} bytes from this file into the byte 461 * array, starting at the current file pointer. This method reads 462 * repeatedly from the file until the requested number of bytes are 463 * read. This method blocks until the requested number of bytes are 464 * read, the end of the stream is detected, or an exception is thrown. 465 * 466 * @param b the buffer into which the data is read. 467 * @throws NullPointerException if {@code b} is {@code null}. 468 * @throws EOFException if this file reaches the end before reading 469 * all the bytes. 470 * @throws IOException if an I/O error occurs. 471 */ 472 public final void readFully(byte[] b) throws IOException { 473 readFully(b, 0, b.length); 474 } 475 476 /** 477 * Reads exactly {@code len} bytes from this file into the byte 478 * array, starting at the current file pointer. This method reads 479 * repeatedly from the file until the requested number of bytes are 480 * read. This method blocks until the requested number of bytes are 481 * read, the end of the stream is detected, or an exception is thrown. 482 * 483 * @param b the buffer into which the data is read. 484 * @param off the start offset into the data array {@code b}. 485 * @param len the number of bytes to read. 486 * @throws NullPointerException if {@code b} is {@code null}. 487 * @throws IndexOutOfBoundsException if {@code off} is negative, 488 * {@code len} is negative, or {@code len} is greater than 489 * {@code b.length - off}. 490 * @throws EOFException if this file reaches the end before reading 491 * all the bytes. 492 * @throws IOException if an I/O error occurs. 493 */ 494 public final void readFully(byte[] b, int off, int len) throws IOException { 495 int n = 0; 496 do { 497 int count = this.read(b, off + n, len - n); 498 if (count < 0) 499 throw new EOFException(); 500 n += count; 501 } while (n < len); 502 } 503 504 /** 505 * Attempts to skip over {@code n} bytes of input discarding the 506 * skipped bytes. 507 * <p> 508 * 509 * This method may skip over some smaller number of bytes, possibly zero. 510 * This may result from any of a number of conditions; reaching end of 511 * file before {@code n} bytes have been skipped is only one 512 * possibility. This method never throws an {@code EOFException}. 513 * The actual number of bytes skipped is returned. If {@code n} 514 * is negative, no bytes are skipped. 515 * 516 * @param n the number of bytes to be skipped. 517 * @return the actual number of bytes skipped. 518 * @throws IOException if an I/O error occurs. 519 */ 520 public int skipBytes(int n) throws IOException { 521 long pos; 522 long len; 523 long newpos; 524 525 if (n <= 0) { 526 return 0; 527 } 528 pos = getFilePointer(); 529 len = length(); 530 newpos = pos + n; 531 if (newpos > len) { 532 newpos = len; 533 } 534 seek(newpos); 535 536 /* return the actual number of bytes skipped */ 537 return (int) (newpos - pos); 538 } 539 540 // 'Write' primitives 541 542 /** 543 * Writes the specified byte to this file. The write starts at 544 * the current file pointer. 545 * 546 * @param b the {@code byte} to be written. 547 * @throws IOException if an I/O error occurs. 548 */ 549 public void write(int b) throws IOException { 550 long comp = Blocker.begin(); 551 try { 552 write0(b); 553 } finally { 554 Blocker.end(comp); 555 } 556 } 557 558 private native void write0(int b) throws IOException; 559 560 /** 561 * Writes a sub array as a sequence of bytes. 562 * 563 * @param b the data to be written 564 * @param off the start offset in the data 565 * @param len the number of bytes that are written 566 * @throws IOException If an I/O error has occurred. 567 */ 568 private void writeBytes(byte[] b, int off, int len) throws IOException { 569 long comp = Blocker.begin(); 570 try { 571 writeBytes0(b, off, len); 572 } finally { 573 Blocker.end(comp); 574 } 575 } 576 577 private native void writeBytes0(byte[] b, int off, int len) throws IOException; 578 579 /** 580 * Writes {@code b.length} bytes from the specified byte array 581 * to this file, starting at the current file pointer. 582 * 583 * @param b the data. 584 * @throws IOException if an I/O error occurs. 585 */ 586 public void write(byte[] b) throws IOException { 587 writeBytes(b, 0, b.length); 588 } 589 590 /** 591 * Writes {@code len} bytes from the specified byte array 592 * starting at offset {@code off} to this file. 593 * 594 * @param b the data. 595 * @param off the start offset in the data. 596 * @param len the number of bytes to write. 597 * @throws IOException if an I/O error occurs. 598 * @throws IndexOutOfBoundsException {@inheritDoc} 599 */ 600 public void write(byte[] b, int off, int len) throws IOException { 601 writeBytes(b, off, len); 602 } 603 604 // 'Random access' stuff 605 606 /** 607 * Returns the current offset in this file. 608 * 609 * @return the offset from the beginning of the file, in bytes, 610 * at which the next read or write occurs. 611 * @throws IOException if an I/O error occurs. 612 */ 613 public native long getFilePointer() throws IOException; 614 615 /** 616 * Sets the file-pointer offset, measured from the beginning of this 617 * file, at which the next read or write occurs. The offset may be 618 * set beyond the end of the file. Setting the offset beyond the end 619 * of the file does not change the file length. The file length will 620 * change only by writing after the offset has been set beyond the end 621 * of the file. 622 * 623 * @param pos the offset position, measured in bytes from the 624 * beginning of the file, at which to set the file 625 * pointer. 626 * @throws IOException if {@code pos} is less than 627 * {@code 0} or if an I/O error occurs. 628 */ 629 public void seek(long pos) throws IOException { 630 if (pos < 0) { 631 throw new IOException("Negative seek offset"); 632 } 633 long comp = Blocker.begin(); 634 try { 635 seek0(pos); 636 } finally { 637 Blocker.end(comp); 638 } 639 } 640 641 private native void seek0(long pos) throws IOException; 642 643 /** 644 * Returns the length of this file. 645 * 646 * @return the length of this file, measured in bytes. 647 * @throws IOException if an I/O error occurs. 648 */ 649 public long length() throws IOException { 650 long comp = Blocker.begin(); 651 try { 652 return length0(); 653 } finally { 654 Blocker.end(comp); 655 } 656 } 657 658 private native long length0() throws IOException; 659 660 /** 661 * Sets the length of this file. 662 * 663 * <p> If the present length of the file as returned by the 664 * {@linkplain #length length} method is greater than the desired length 665 * of the file specified by the {@code newLength} argument, then the file 666 * will be truncated. 667 * 668 * <p> If the present length of the file is smaller than the desired length, 669 * then the file will be extended. The contents of the extended portion of 670 * the file are not defined. 671 * 672 * <p> If the present length of the file is equal to the desired length, 673 * then the file and its length will be unchanged. 674 * 675 * <p> In all cases, after this method returns, the file offset as returned 676 * by the {@linkplain #getFilePointer getFilePointer} method will equal the 677 * minimum of the desired length and the file offset before this method was 678 * called, even if the length is unchanged. In other words, this method 679 * constrains the file offset to the closed interval {@code [0,newLength]}. 680 * 681 * @param newLength The desired length of the file 682 * @throws IOException If the argument is negative or 683 * if some other I/O error occurs 684 * @since 1.2 685 */ 686 public void setLength(long newLength) throws IOException { 687 long comp = Blocker.begin(); 688 try { 689 setLength0(newLength); 690 } finally { 691 Blocker.end(comp); 692 } 693 } 694 695 private native void setLength0(long newLength) throws IOException; 696 697 /** 698 * Closes this random access file stream and releases any system 699 * resources associated with the stream. A closed random access 700 * file cannot perform input or output operations and cannot be 701 * reopened. 702 * 703 * <p> If this file has an associated channel then the channel is closed 704 * as well. 705 * 706 * @apiNote 707 * If this stream has an associated channel then this method will close the 708 * channel, which in turn will close this stream. Subclasses that override 709 * this method should be prepared to handle possible reentrant invocation. 710 * 711 * @throws IOException if an I/O error occurs. 712 */ 713 public void close() throws IOException { 714 if (closed) { 715 return; 716 } 717 synchronized (closeLock) { 718 if (closed) { 719 return; 720 } 721 closed = true; 722 } 723 724 FileChannel fc = channel; 725 if (fc != null) { 726 // possible race with getChannel(), benign since 727 // FileChannel.close is final and idempotent 728 fc.close(); 729 } 730 731 fd.closeAll(new Closeable() { 732 public void close() throws IOException { 733 fd.close(); 734 } 735 }); 736 } 737 738 // 739 // Some "reading/writing Java data types" methods stolen from 740 // DataInputStream and DataOutputStream. 741 // 742 743 /** 744 * Reads a {@code boolean} from this file. This method reads a 745 * single byte from the file, starting at the current file pointer. 746 * A value of {@code 0} represents 747 * {@code false}. Any other value represents {@code true}. 748 * This method blocks until the byte is read, the end of the stream 749 * is detected, or an exception is thrown. 750 * 751 * @return the {@code boolean} value read. 752 * @throws EOFException if this file has reached the end. 753 * @throws IOException if an I/O error occurs. 754 */ 755 public final boolean readBoolean() throws IOException { 756 return readUnsignedByte() != 0; 757 } 758 759 /** 760 * Reads a signed eight-bit value from this file. This method reads a 761 * byte from the file, starting from the current file pointer. 762 * If the byte read is {@code b}, where 763 * {@code 0 <= b <= 255}, 764 * then the result is: 765 * {@snippet lang=java : 766 * (byte)(b) 767 * } 768 * <p> 769 * This method blocks until the byte is read, the end of the stream 770 * is detected, or an exception is thrown. 771 * 772 * @return the next byte of this file as a signed eight-bit 773 * {@code byte}. 774 * @throws EOFException if this file has reached the end. 775 * @throws IOException if an I/O error occurs. 776 */ 777 public final byte readByte() throws IOException { 778 return (byte) readUnsignedByte(); 779 } 780 781 /** 782 * Reads an unsigned eight-bit number from this file. This method reads 783 * a byte from this file, starting at the current file pointer, 784 * and returns that byte. 785 * <p> 786 * This method blocks until the byte is read, the end of the stream 787 * is detected, or an exception is thrown. 788 * 789 * @return the next byte of this file, interpreted as an unsigned 790 * eight-bit number. 791 * @throws EOFException if this file has reached the end. 792 * @throws IOException if an I/O error occurs. 793 */ 794 public final int readUnsignedByte() throws IOException { 795 int ch = this.read(); 796 if (ch < 0) 797 throw new EOFException(); 798 return ch; 799 } 800 801 /** 802 * Reads a signed 16-bit number from this file. The method reads two 803 * bytes from this file, starting at the current file pointer. 804 * If the two bytes read, in order, are 805 * {@code b1} and {@code b2}, where each of the two values is 806 * between {@code 0} and {@code 255}, inclusive, then the 807 * result is equal to: 808 * {@snippet lang=java : 809 * (short)((b1 << 8) | b2) 810 * } 811 * <p> 812 * This method blocks until the two bytes are read, the end of the 813 * stream is detected, or an exception is thrown. 814 * 815 * @return the next two bytes of this file, interpreted as a signed 816 * 16-bit number. 817 * @throws EOFException if this file reaches the end before reading 818 * two bytes. 819 * @throws IOException if an I/O error occurs. 820 */ 821 public final short readShort() throws IOException { 822 return (short) readUnsignedShort(); 823 } 824 825 /** 826 * Reads an unsigned 16-bit number from this file. This method reads 827 * two bytes from the file, starting at the current file pointer. 828 * If the bytes read, in order, are 829 * {@code b1} and {@code b2}, where 830 * {@code 0 <= b1, b2 <= 255}, 831 * then the result is equal to: 832 * {@snippet lang=java : 833 * (b1 << 8) | b2 834 * } 835 * <p> 836 * This method blocks until the two bytes are read, the end of the 837 * stream is detected, or an exception is thrown. 838 * 839 * @return the next two bytes of this file, interpreted as an unsigned 840 * 16-bit integer. 841 * @throws EOFException if this file reaches the end before reading 842 * two bytes. 843 * @throws IOException if an I/O error occurs. 844 */ 845 public final int readUnsignedShort() throws IOException { 846 readFully(buffer, 0, Short.BYTES); 847 return ((buffer[1] & 0xff) ) + 848 ((buffer[0] & 0xff) << 8); 849 } 850 851 /** 852 * Reads a character from this file. This method reads two 853 * bytes from the file, starting at the current file pointer. 854 * If the bytes read, in order, are 855 * {@code b1} and {@code b2}, where 856 * {@code 0 <= b1, b2 <= 255}, 857 * then the result is equal to: 858 * {@snippet lang=java : 859 * (char)((b1 << 8) | b2) 860 * } 861 * <p> 862 * This method blocks until the two bytes are read, the end of the 863 * stream is detected, or an exception is thrown. 864 * 865 * @return the next two bytes of this file, interpreted as a 866 * {@code char}. 867 * @throws EOFException if this file reaches the end before reading 868 * two bytes. 869 * @throws IOException if an I/O error occurs. 870 */ 871 public final char readChar() throws IOException { 872 return (char) readUnsignedShort(); 873 } 874 875 /** 876 * Reads a signed 32-bit integer from this file. This method reads 4 877 * bytes from the file, starting at the current file pointer. 878 * If the bytes read, in order, are {@code b1}, 879 * {@code b2}, {@code b3}, and {@code b4}, where 880 * {@code 0 <= b1, b2, b3, b4 <= 255}, 881 * then the result is equal to: 882 * {@snippet lang=java : 883 * (b1 << 24) | (b2 << 16) + (b3 << 8) + b4 884 * } 885 * <p> 886 * This method blocks until the four bytes are read, the end of the 887 * stream is detected, or an exception is thrown. 888 * 889 * @return the next four bytes of this file, interpreted as an 890 * {@code int}. 891 * @throws EOFException if this file reaches the end before reading 892 * four bytes. 893 * @throws IOException if an I/O error occurs. 894 */ 895 public final int readInt() throws IOException { 896 readFully(buffer, 0, Integer.BYTES); 897 return ByteArray.getInt(buffer, 0); 898 } 899 900 /** 901 * Reads a signed 64-bit integer from this file. This method reads eight 902 * bytes from the file, starting at the current file pointer. 903 * If the bytes read, in order, are 904 * {@code b1}, {@code b2}, {@code b3}, 905 * {@code b4}, {@code b5}, {@code b6}, 906 * {@code b7}, and {@code b8,} where: 907 * {@snippet : 908 * 0 <= b1, b2, b3, b4, b5, b6, b7, b8 <= 255 909 * } 910 * <p> 911 * then the result is equal to: 912 * {@snippet lang=java : 913 * ((long)b1 << 56) + ((long)b2 << 48) 914 * + ((long)b3 << 40) + ((long)b4 << 32) 915 * + ((long)b5 << 24) + ((long)b6 << 16) 916 * + ((long)b7 << 8) + b8 917 * } 918 * <p> 919 * This method blocks until the eight bytes are read, the end of the 920 * stream is detected, or an exception is thrown. 921 * 922 * @return the next eight bytes of this file, interpreted as a 923 * {@code long}. 924 * @throws EOFException if this file reaches the end before reading 925 * eight bytes. 926 * @throws IOException if an I/O error occurs. 927 */ 928 public final long readLong() throws IOException { 929 readFully(buffer, 0, Long.BYTES); 930 return ByteArray.getLong(buffer, 0); 931 } 932 933 /** 934 * Reads a {@code float} from this file. This method reads an 935 * {@code int} value, starting at the current file pointer, 936 * as if by the {@code readInt} method 937 * and then converts that {@code int} to a {@code float} 938 * using the {@code intBitsToFloat} method in class 939 * {@code Float}. 940 * <p> 941 * This method blocks until the four bytes are read, the end of the 942 * stream is detected, or an exception is thrown. 943 * 944 * @return the next four bytes of this file, interpreted as a 945 * {@code float}. 946 * @throws EOFException if this file reaches the end before reading 947 * four bytes. 948 * @throws IOException if an I/O error occurs. 949 * @see java.io.RandomAccessFile#readInt() 950 * @see java.lang.Float#intBitsToFloat(int) 951 */ 952 public final float readFloat() throws IOException { 953 readFully(buffer, 0, Float.BYTES); 954 return ByteArray.getFloat(buffer, 0); 955 } 956 957 /** 958 * Reads a {@code double} from this file. This method reads a 959 * {@code long} value, starting at the current file pointer, 960 * as if by the {@code readLong} method 961 * and then converts that {@code long} to a {@code double} 962 * using the {@code longBitsToDouble} method in 963 * class {@code Double}. 964 * <p> 965 * This method blocks until the eight bytes are read, the end of the 966 * stream is detected, or an exception is thrown. 967 * 968 * @return the next eight bytes of this file, interpreted as a 969 * {@code double}. 970 * @throws EOFException if this file reaches the end before reading 971 * eight bytes. 972 * @throws IOException if an I/O error occurs. 973 * @see java.io.RandomAccessFile#readLong() 974 * @see java.lang.Double#longBitsToDouble(long) 975 */ 976 public final double readDouble() throws IOException { 977 readFully(buffer, 0, Double.BYTES); 978 return ByteArray.getDouble(buffer, 0); 979 } 980 981 /** 982 * Reads the next line of text from this file. This method successively 983 * reads bytes from the file, starting at the current file pointer, 984 * until it reaches a line terminator or the end 985 * of the file. Each byte is converted into a character by taking the 986 * byte's value for the lower eight bits of the character and setting the 987 * high eight bits of the character to zero. This method does not, 988 * therefore, support the full Unicode character set. 989 * 990 * <p> A line of text is terminated by a carriage-return character 991 * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a 992 * carriage-return character immediately followed by a newline character, 993 * or the end of the file. Line-terminating characters are discarded and 994 * are not included as part of the string returned. 995 * 996 * <p> This method blocks until a newline character is read, a carriage 997 * return and the byte following it are read (to see if it is a newline), 998 * the end of the file is reached, or an exception is thrown. 999 * 1000 * @return the next line of text from this file, or null if end 1001 * of file is encountered before even one byte is read. 1002 * @throws IOException if an I/O error occurs. 1003 */ 1004 1005 public final String readLine() throws IOException { 1006 StringBuilder input = new StringBuilder(); 1007 int c = -1; 1008 boolean eol = false; 1009 1010 while (!eol) { 1011 switch (c = read()) { 1012 case -1, '\n' -> eol = true; 1013 case '\r' -> { 1014 eol = true; 1015 long cur = getFilePointer(); 1016 if ((read()) != '\n') { 1017 seek(cur); 1018 } 1019 } 1020 default -> input.append((char) c); 1021 } 1022 } 1023 1024 if ((c == -1) && (input.length() == 0)) { 1025 return null; 1026 } 1027 return input.toString(); 1028 } 1029 1030 /** 1031 * Reads in a string from this file. The string has been encoded 1032 * using a 1033 * <a href="DataInput.html#modified-utf-8">modified UTF-8</a> 1034 * format. 1035 * <p> 1036 * The first two bytes are read, starting from the current file 1037 * pointer, as if by 1038 * {@code readUnsignedShort}. This value gives the number of 1039 * following bytes that are in the encoded string, not 1040 * the length of the resulting string. The following bytes are then 1041 * interpreted as bytes encoding characters in the modified UTF-8 format 1042 * and are converted into characters. 1043 * <p> 1044 * This method blocks until all the bytes are read, the end of the 1045 * stream is detected, or an exception is thrown. 1046 * 1047 * @return a Unicode string. 1048 * @throws EOFException if this file reaches the end before 1049 * reading all the bytes. 1050 * @throws IOException if an I/O error occurs. 1051 * @throws UTFDataFormatException if the bytes do not represent 1052 * valid modified UTF-8 encoding of a Unicode string. 1053 * @see java.io.RandomAccessFile#readUnsignedShort() 1054 */ 1055 public final String readUTF() throws IOException { 1056 return DataInputStream.readUTF(this); 1057 } 1058 1059 /** 1060 * Writes a {@code boolean} to the file as a one-byte value. The 1061 * value {@code true} is written out as the value 1062 * {@code (byte)1}; the value {@code false} is written out 1063 * as the value {@code (byte)0}. The write starts at 1064 * the current position of the file pointer. 1065 * 1066 * @param v a {@code boolean} value to be written. 1067 * @throws IOException if an I/O error occurs. 1068 */ 1069 public final void writeBoolean(boolean v) throws IOException { 1070 write(v ? 1 : 0); 1071 } 1072 1073 /** 1074 * Writes a {@code byte} to the file as a one-byte value. The 1075 * write starts at the current position of the file pointer. 1076 * 1077 * @param v a {@code byte} value to be written. 1078 * @throws IOException if an I/O error occurs. 1079 */ 1080 public final void writeByte(int v) throws IOException { 1081 write(v); 1082 } 1083 1084 /** 1085 * Writes a {@code short} to the file as two bytes, high byte first. 1086 * The write starts at the current position of the file pointer. 1087 * 1088 * @param v a {@code short} to be written. 1089 * @throws IOException if an I/O error occurs. 1090 */ 1091 public final void writeShort(int v) throws IOException { 1092 buffer[1] = (byte)(v ); 1093 buffer[0] = (byte)(v >>> 8); 1094 write(buffer, 0, Short.BYTES); 1095 } 1096 1097 /** 1098 * Writes a {@code char} to the file as a two-byte value, high 1099 * byte first. The write starts at the current position of the 1100 * file pointer. 1101 * 1102 * @param v a {@code char} value to be written. 1103 * @throws IOException if an I/O error occurs. 1104 */ 1105 public final void writeChar(int v) throws IOException { 1106 writeShort(v); 1107 } 1108 1109 /** 1110 * Writes an {@code int} to the file as four bytes, high byte first. 1111 * The write starts at the current position of the file pointer. 1112 * 1113 * @param v an {@code int} to be written. 1114 * @throws IOException if an I/O error occurs. 1115 */ 1116 public final void writeInt(int v) throws IOException { 1117 ByteArray.setInt(buffer, 0, v); 1118 write(buffer, 0, Integer.BYTES); 1119 //written += 4; 1120 } 1121 1122 /** 1123 * Writes a {@code long} to the file as eight bytes, high byte first. 1124 * The write starts at the current position of the file pointer. 1125 * 1126 * @param v a {@code long} to be written. 1127 * @throws IOException if an I/O error occurs. 1128 */ 1129 public final void writeLong(long v) throws IOException { 1130 ByteArray.setLong(buffer, 0, v); 1131 write(buffer, 0, Long.BYTES); 1132 } 1133 1134 /** 1135 * Converts the float argument to an {@code int} using the 1136 * {@code floatToIntBits} method in class {@code Float}, 1137 * and then writes that {@code int} value to the file as a 1138 * four-byte quantity, high byte first. The write starts at the 1139 * current position of the file pointer. 1140 * 1141 * @param v a {@code float} value to be written. 1142 * @throws IOException if an I/O error occurs. 1143 * @see java.lang.Float#floatToIntBits(float) 1144 */ 1145 public final void writeFloat(float v) throws IOException { 1146 ByteArray.setFloat(buffer, 0, v); 1147 write(buffer, 0, Float.BYTES); 1148 } 1149 1150 /** 1151 * Converts the double argument to a {@code long} using the 1152 * {@code doubleToLongBits} method in class {@code Double}, 1153 * and then writes that {@code long} value to the file as an 1154 * eight-byte quantity, high byte first. The write starts at the current 1155 * position of the file pointer. 1156 * 1157 * @param v a {@code double} value to be written. 1158 * @throws IOException if an I/O error occurs. 1159 * @see java.lang.Double#doubleToLongBits(double) 1160 */ 1161 public final void writeDouble(double v) throws IOException { 1162 ByteArray.setDouble(buffer, 0, v); 1163 write(buffer, 0, Double.BYTES); 1164 } 1165 1166 /** 1167 * Writes the string to the file as a sequence of bytes. Each 1168 * character in the string is written out, in sequence, by discarding 1169 * its high eight bits. The write starts at the current position of 1170 * the file pointer. 1171 * 1172 * @param s a string of bytes to be written. 1173 * @throws IOException if an I/O error occurs. 1174 */ 1175 @SuppressWarnings("deprecation") 1176 public final void writeBytes(String s) throws IOException { 1177 int len = s.length(); 1178 byte[] b = new byte[len]; 1179 s.getBytes(0, len, b, 0); 1180 writeBytes(b, 0, len); 1181 } 1182 1183 /** 1184 * Writes a string to the file as a sequence of characters. Each 1185 * character is written to the data output stream as if by the 1186 * {@code writeChar} method. The write starts at the current 1187 * position of the file pointer. 1188 * 1189 * @param s a {@code String} value to be written. 1190 * @throws IOException if an I/O error occurs. 1191 * @see java.io.RandomAccessFile#writeChar(int) 1192 */ 1193 public final void writeChars(String s) throws IOException { 1194 int clen = s.length(); 1195 int blen = 2*clen; 1196 byte[] b = new byte[blen]; 1197 char[] c = new char[clen]; 1198 s.getChars(0, clen, c, 0); 1199 for (int i = 0, j = 0; i < clen; i++) { 1200 b[j++] = (byte)(c[i] >>> 8); 1201 b[j++] = (byte)(c[i] >>> 0); 1202 } 1203 writeBytes(b, 0, blen); 1204 } 1205 1206 /** 1207 * Writes a string to the file using 1208 * <a href="DataInput.html#modified-utf-8">modified UTF-8</a> 1209 * encoding in a machine-independent manner. 1210 * <p> 1211 * First, two bytes are written to the file, starting at the 1212 * current file pointer, as if by the 1213 * {@code writeShort} method giving the number of bytes to 1214 * follow. This value is the number of bytes actually written out, 1215 * not the length of the string. Following the length, each character 1216 * of the string is output, in sequence, using the modified UTF-8 encoding 1217 * for each character. 1218 * 1219 * @param str a string to be written. 1220 * @throws IOException if an I/O error occurs. 1221 */ 1222 public final void writeUTF(String str) throws IOException { 1223 DataOutputStream.writeUTF(str, this); 1224 } 1225 1226 private static native void initIDs(); 1227 1228 static { 1229 initIDs(); 1230 SharedSecrets.setJavaIORandomAccessFileAccess(new JavaIORandomAccessFileAccess() 1231 { 1232 // This is for j.u.z.ZipFile.OPEN_DELETE. The O_TEMPORARY flag 1233 // is only implemented/supported on Windows. 1234 public RandomAccessFile openAndDelete(File file, String mode) 1235 throws IOException 1236 { 1237 return new RandomAccessFile(file, mode, true); 1238 } 1239 }); 1240 } 1241 }