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