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