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