1125 lines · 45.1 KB · Java
RawDownload
/* * Copyright (c) 1994, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.nio.channels.FileChannel;import sun.nio.ch.FileChannelImpl;  /** * Instances of this class support both reading and writing to a * random access file. A random access file behaves like a large * array of bytes stored in the file system. There is a kind of cursor, * or index into the implied array, called the <em>file pointer</em>; * input operations read bytes starting at the file pointer and advance * the file pointer past the bytes read. If the random access file is * created in read/write mode, then output operations are also available; * output operations write bytes starting at the file pointer and advance * the file pointer past the bytes written. Output operations that write * past the current end of the implied array cause the array to be * extended. The file pointer can be read by the * <code>getFilePointer</code> method and set by the <code>seek</code> * method. * <p> * It is generally true of all the reading routines in this class that * if end-of-file is reached before the desired number of bytes has been * read, an <code>EOFException</code> (which is a kind of * <code>IOException</code>) is thrown. If any byte cannot be read for * any reason other than end-of-file, an <code>IOException</code> other * than <code>EOFException</code> is thrown. In particular, an * <code>IOException</code> may be thrown if the stream has been closed. * * @author  unascribed * @since   JDK1.0 */ public class RandomAccessFile implements DataOutput, DataInput, Closeable {     private FileDescriptor fd;    private FileChannel channel = null;    private boolean rw;     private Object closeLock = new Object();    private volatile boolean closed = false;     private static final int O_RDONLY = 1;    private static final int O_RDWR =   2;    private static final int O_SYNC =   4;    private static final int O_DSYNC =  8;     /**     * Creates a random access file stream to read from, and optionally     * to write to, a file with the specified name. A new     * {@link FileDescriptor} object is created to represent the     * connection to the file.     *     * <p> The <tt>mode</tt> argument specifies the access mode with which the     * file is to be opened.  The permitted values and their meanings are as     * specified for the <a     * href="#mode"><tt>RandomAccessFile(File,String)</tt></a> constructor.     *     * <p>     * If there is a security manager, its <code>checkRead</code> method     * is called with the <code>name</code> argument     * as its argument to see if read access to the file is allowed.     * If the mode allows writing, the security manager's     * <code>checkWrite</code> method     * is also called with the <code>name</code> argument     * as its argument to see if write access to the file is allowed.     *     * @param      name   the system-dependent filename     * @param      mode   the access <a href="#mode">mode</a>     * @exception  IllegalArgumentException  if the mode argument is not equal     *               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or     *               <tt>"rwd"</tt>     * @exception FileNotFoundException     *            if the mode is <tt>"r"</tt> but the given string does not     *            denote an existing regular file, or if the mode begins with     *            <tt>"rw"</tt> but the given string does not denote an     *            existing, writable regular file and a new regular file of     *            that name cannot be created, or if some other error occurs     *            while opening or creating the file     * @exception  SecurityException         if a security manager exists and its     *               <code>checkRead</code> method denies read access to the file     *               or the mode is "rw" and the security manager's     *               <code>checkWrite</code> method denies write access to the file     * @see        java.lang.SecurityException     * @see        java.lang.SecurityManager#checkRead(java.lang.String)     * @see        java.lang.SecurityManager#checkWrite(java.lang.String)     * @revised 1.4     * @spec JSR-51     */    public RandomAccessFile(String name, String mode)        throws FileNotFoundException    {        this(name != null ? new File(name) : null, mode);    }     /**     * Creates a random access file stream to read from, and optionally to     * write to, the file specified by the {@link File} argument.  A new {@link     * FileDescriptor} object is created to represent this file connection.     *     * <a name="mode"><p> The <tt>mode</tt> argument specifies the access mode     * in which the file is to be opened.  The permitted values and their     * meanings are:     *     * <blockquote><table summary="Access mode permitted values and meanings">     * <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>     * <tr><td valign="top"><tt>"r"</tt></td>     *     <td> Open for reading only.  Invoking any of the <tt>write</tt>     *     methods of the resulting object will cause an {@link     *     java.io.IOException} to be thrown. </td></tr>     * <tr><td valign="top"><tt>"rw"</tt></td>     *     <td> Open for reading and writing.  If the file does not already     *     exist then an attempt will be made to create it. </td></tr>     * <tr><td valign="top"><tt>"rws"</tt></td>     *     <td> Open for reading and writing, as with <tt>"rw"</tt>, and also     *     require that every update to the file's content or metadata be     *     written synchronously to the underlying storage device.  </td></tr>     * <tr><td valign="top"><tt>"rwd"&nbsp;&nbsp;</tt></td>     *     <td> Open for reading and writing, as with <tt>"rw"</tt>, and also     *     require that every update to the file's content be written     *     synchronously to the underlying storage device. </td></tr>     * </table></blockquote>     *     * The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link     * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of     * the {@link java.nio.channels.FileChannel} class, passing arguments of     * <tt>true</tt> and <tt>false</tt>, respectively, except that they always     * apply to every I/O operation and are therefore often more efficient.  If     * the file resides on a local storage device then when an invocation of a     * method of this class returns it is guaranteed that all changes made to     * the file by that invocation will have been written to that device.  This     * is useful for ensuring that critical information is not lost in the     * event of a system crash.  If the file does not reside on a local device     * then no such guarantee is made.     *     * <p> The <tt>"rwd"</tt> mode can be used to reduce the number of I/O     * operations performed.  Using <tt>"rwd"</tt> only requires updates to the     * file's content to be written to storage; using <tt>"rws"</tt> requires     * updates to both the file's content and its metadata to be written, which     * generally requires at least one more low-level I/O operation.     *     * <p> If there is a security manager, its <code>checkRead</code> method is     * called with the pathname of the <code>file</code> argument as its     * argument to see if read access to the file is allowed.  If the mode     * allows writing, the security manager's <code>checkWrite</code> method is     * also called with the path argument to see if write access to the file is     * allowed.     *     * @param      file   the file object     * @param      mode   the access mode, as described     *                    <a href="#mode">above</a>     * @exception  IllegalArgumentException  if the mode argument is not equal     *               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or     *               <tt>"rwd"</tt>     * @exception FileNotFoundException     *            if the mode is <tt>"r"</tt> but the given file object does     *            not denote an existing regular file, or if the mode begins     *            with <tt>"rw"</tt> but the given file object does not denote     *            an existing, writable regular file and a new regular file of     *            that name cannot be created, or if some other error occurs     *            while opening or creating the file     * @exception  SecurityException         if a security manager exists and its     *               <code>checkRead</code> method denies read access to the file     *               or the mode is "rw" and the security manager's     *               <code>checkWrite</code> method denies write access to the file     * @see        java.lang.SecurityManager#checkRead(java.lang.String)     * @see        java.lang.SecurityManager#checkWrite(java.lang.String)     * @see        java.nio.channels.FileChannel#force(boolean)     * @revised 1.4     * @spec JSR-51     */    public RandomAccessFile(File file, String mode)        throws FileNotFoundException    {        String name = (file != null ? file.getPath() : null);        int imode = -1;        if (mode.equals("r"))            imode = O_RDONLY;        else if (mode.startsWith("rw")) {            imode = O_RDWR;            rw = true;            if (mode.length() > 2) {                if (mode.equals("rws"))                    imode |= O_SYNC;                else if (mode.equals("rwd"))                    imode |= O_DSYNC;                else                    imode = -1;            }        }        if (imode < 0)            throw new IllegalArgumentException("Illegal mode \"" + mode                                               + "\" must be one of "                                               + "\"r\", \"rw\", \"rws\","                                               + " or \"rwd\"");        SecurityManager security = System.getSecurityManager();        if (security != null) {            security.checkRead(name);            if (rw) {                security.checkWrite(name);            }        }        if (name == null) {            throw new NullPointerException();        }        fd = new FileDescriptor();        fd.incrementAndGetUseCount();        open(name, imode);    }     /**     * Returns the opaque file descriptor object associated with this     * stream. </p>     *     * @return     the file descriptor object associated with this stream.     * @exception  IOException  if an I/O error occurs.     * @see        java.io.FileDescriptor     */    public final FileDescriptor getFD() throws IOException {        if (fd != null) return fd;        throw new IOException();    }     /**     * Returns the unique {@link java.nio.channels.FileChannel FileChannel}     * object associated with this file.     *     * <p> The {@link java.nio.channels.FileChannel#position()     * </code>position<code>} of the returned channel will always be equal to     * this object's file-pointer offset as returned by the {@link     * #getFilePointer getFilePointer} method.  Changing this object's     * file-pointer offset, whether explicitly or by reading or writing bytes,     * will change the position of the channel, and vice versa.  Changing the     * file's length via this object will change the length seen via the file     * channel, and vice versa.     *     * @return  the file channel associated with this file     *     * @since 1.4     * @spec JSR-51     */    public final FileChannel getChannel() {        synchronized (this) {            if (channel == null) {                channel = FileChannelImpl.open(fd, true, rw, this);                 /*                 * FileDescriptor could be shared by FileInputStream or                 * FileOutputStream.                 * Ensure that FD is GC'ed only when all the streams/channels                 * are done using it.                 * Increment fd's use count. Invoking the channel's close()                 * method will result in decrementing the use count set for                 * the channel.                 */                fd.incrementAndGetUseCount();            }            return channel;        }    }     /**     * Opens a file and returns the file descriptor.  The file is     * opened in read-write mode if the O_RDWR bit in <code>mode</code>     * is true, else the file is opened as read-only.     * If the <code>name</code> refers to a directory, an IOException     * is thrown.     *     * @param name the name of the file     * @param mode the mode flags, a combination of the O_ constants     *             defined above     */    private native void open(String name, int mode)        throws FileNotFoundException;     // 'Read' primitives     /**     * Reads a byte of data from this file. The byte is returned as an     * integer in the range 0 to 255 (<code>0x00-0x0ff</code>). This     * method blocks if no input is yet available.     * <p>     * Although <code>RandomAccessFile</code> is not a subclass of     * <code>InputStream</code>, this method behaves in exactly the same     * way as the {@link InputStream#read()} method of     * <code>InputStream</code>.     *     * @return     the next byte of data, or <code>-1</code> if the end of the     *             file has been reached.     * @exception  IOException  if an I/O error occurs. Not thrown if     *                          end-of-file has been reached.     */    public native int read() throws IOException;     /**     * Reads a sub array as a sequence of bytes.     * @param b the buffer into which the data is read.     * @param off the start offset of the data.     * @param len the number of bytes to read.     * @exception IOException If an I/O error has occurred.     */    private native int readBytes(byte b[], int off, int len) throws IOException;     /**     * Reads up to <code>len</code> bytes of data from this file into an     * array of bytes. This method blocks until at least one byte of input     * is available.     * <p>     * Although <code>RandomAccessFile</code> is not a subclass of     * <code>InputStream</code>, this method behaves in exactly the     * same way as the {@link InputStream#read(byte[], int, int)} method of     * <code>InputStream</code>.     *     * @param      b     the buffer into which the data is read.     * @param      off   the start offset in array <code>b</code>     *                   at which the data is written.     * @param      len   the maximum number of bytes read.     * @return     the total number of bytes read into the buffer, or     *             <code>-1</code> if there is no more data because the end of     *             the file has been reached.     * @exception  IOException If the first byte cannot be read for any reason     * other than end of file, or if the random access file has been closed, or if     * some other I/O error occurs.     * @exception  NullPointerException If <code>b</code> is <code>null</code>.     * @exception  IndexOutOfBoundsException If <code>off</code> is negative,     * <code>len</code> is negative, or <code>len</code> is greater than     * <code>b.length - off</code>     */    public int read(byte b[], int off, int len) throws IOException {        return readBytes(b, off, len);    }     /**     * Reads up to <code>b.length</code> bytes of data from this file     * into an array of bytes. This method blocks until at least one byte     * of input is available.     * <p>     * Although <code>RandomAccessFile</code> is not a subclass of     * <code>InputStream</code>, this method behaves in exactly the     * same way as the {@link InputStream#read(byte[])} method of     * <code>InputStream</code>.     *     * @param      b   the buffer into which the data is read.     * @return     the total number of bytes read into the buffer, or     *             <code>-1</code> if there is no more data because the end of     *             this file has been reached.     * @exception  IOException If the first byte cannot be read for any reason     * other than end of file, or if the random access file has been closed, or if     * some other I/O error occurs.     * @exception  NullPointerException If <code>b</code> is <code>null</code>.     */    public int read(byte b[]) throws IOException {        return readBytes(b, 0, b.length);    }     /**     * Reads <code>b.length</code> bytes from this file into the byte     * array, starting at the current file pointer. This method reads     * repeatedly from the file until the requested number of bytes are     * read. This method blocks until the requested number of bytes are     * read, the end of the stream is detected, or an exception is thrown.     *     * @param      b   the buffer into which the data is read.     * @exception  EOFException  if this file reaches the end before reading     *               all the bytes.     * @exception  IOException   if an I/O error occurs.     */    public final void readFully(byte b[]) throws IOException {        readFully(b, 0, b.length);    }     /**     * Reads exactly <code>len</code> bytes from this file into the byte     * array, starting at the current file pointer. This method reads     * repeatedly from the file until the requested number of bytes are     * read. This method blocks until the requested number of bytes are     * read, the end of the stream is detected, or an exception is thrown.     *     * @param      b     the buffer into which the data is read.     * @param      off   the start offset of the data.     * @param      len   the number of bytes to read.     * @exception  EOFException  if this file reaches the end before reading     *               all the bytes.     * @exception  IOException   if an I/O error occurs.     */    public final void readFully(byte b[], int off, int len) throws IOException {        int n = 0;        do {            int count = this.read(b, off + n, len - n);            if (count < 0)                throw new EOFException();            n += count;        } while (n < len);    }     /**     * Attempts to skip over <code>n</code> bytes of input discarding the     * skipped bytes.     * <p>     *     * This method may skip over some smaller number of bytes, possibly zero.     * This may result from any of a number of conditions; reaching end of     * file before <code>n</code> bytes have been skipped is only one     * possibility. This method never throws an <code>EOFException</code>.     * The actual number of bytes skipped is returned.  If <code>n</code>     * is negative, no bytes are skipped.     *     * @param      n   the number of bytes to be skipped.     * @return     the actual number of bytes skipped.     * @exception  IOException  if an I/O error occurs.     */    public int skipBytes(int n) throws IOException {        long pos;        long len;        long newpos;         if (n <= 0) {            return 0;        }        pos = getFilePointer();        len = length();        newpos = pos + n;        if (newpos > len) {            newpos = len;        }        seek(newpos);         /* return the actual number of bytes skipped */        return (int) (newpos - pos);    }     // 'Write' primitives     /**     * Writes the specified byte to this file. The write starts at     * the current file pointer.     *     * @param      b   the <code>byte</code> to be written.     * @exception  IOException  if an I/O error occurs.     */    public native void write(int b) throws IOException;     /**     * Writes a sub array as a sequence of bytes.     * @param b the data to be written      * @param off the start offset in the data     * @param len the number of bytes that are written     * @exception IOException If an I/O error has occurred.     */    private native void writeBytes(byte b[], int off, int len) throws IOException;     /**     * Writes <code>b.length</code> bytes from the specified byte array     * to this file, starting at the current file pointer.     *     * @param      b   the data.     * @exception  IOException  if an I/O error occurs.     */    public void write(byte b[]) throws IOException {        writeBytes(b, 0, b.length);    }     /**     * Writes <code>len</code> bytes from the specified byte array     * starting at offset <code>off</code> to this file.     *     * @param      b     the data.     * @param      off   the start offset in the data.     * @param      len   the number of bytes to write.     * @exception  IOException  if an I/O error occurs.     */    public void write(byte b[], int off, int len) throws IOException {        writeBytes(b, off, len);    }

Lines 1–500 of 1125.