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