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