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