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