Source Code Cross Referenced for RandomAccessFile.java in  » 6.0-JDK-Core » io-nio » java » io » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » io nio » java.io 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001        /*
0002         * Copyright 1994-2007 Sun Microsystems, Inc.  All Rights Reserved.
0003         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004         *
0005         * This code is free software; you can redistribute it and/or modify it
0006         * under the terms of the GNU General Public License version 2 only, as
0007         * published by the Free Software Foundation.  Sun designates this
0008         * particular file as subject to the "Classpath" exception as provided
0009         * by Sun in the LICENSE file that accompanied this code.
0010         *
0011         * This code is distributed in the hope that it will be useful, but WITHOUT
0012         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
0014         * version 2 for more details (a copy is included in the LICENSE file that
0015         * accompanied this code).
0016         *
0017         * You should have received a copy of the GNU General Public License version
0018         * 2 along with this work; if not, write to the Free Software Foundation,
0019         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020         *
0021         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022         * CA 95054 USA or visit www.sun.com if you need additional information or
0023         * have any questions.
0024         */
0025
0026        package java.io;
0027
0028        import java.nio.channels.FileChannel;
0029        import sun.nio.ch.FileChannelImpl;
0030
0031        /**
0032         * Instances of this class support both reading and writing to a 
0033         * random access file. A random access file behaves like a large 
0034         * array of bytes stored in the file system. There is a kind of cursor, 
0035         * or index into the implied array, called the <em>file pointer</em>; 
0036         * input operations read bytes starting at the file pointer and advance 
0037         * the file pointer past the bytes read. If the random access file is 
0038         * created in read/write mode, then output operations are also available; 
0039         * output operations write bytes starting at the file pointer and advance 
0040         * the file pointer past the bytes written. Output operations that write 
0041         * past the current end of the implied array cause the array to be 
0042         * extended. The file pointer can be read by the 
0043         * <code>getFilePointer</code> method and set by the <code>seek</code> 
0044         * method. 
0045         * <p>
0046         * It is generally true of all the reading routines in this class that 
0047         * if end-of-file is reached before the desired number of bytes has been 
0048         * read, an <code>EOFException</code> (which is a kind of 
0049         * <code>IOException</code>) is thrown. If any byte cannot be read for 
0050         * any reason other than end-of-file, an <code>IOException</code> other 
0051         * than <code>EOFException</code> is thrown. In particular, an 
0052         * <code>IOException</code> may be thrown if the stream has been closed.
0053         *
0054         * @author  unascribed
0055         * @version 1.90, 06/13/07
0056         * @since   JDK1.0
0057         */
0058
0059        public class RandomAccessFile implements  DataOutput, DataInput,
0060                Closeable {
0061
0062            private FileDescriptor fd;
0063            private FileChannel channel = null;
0064            private boolean rw;
0065
0066            private Object closeLock = new Object();
0067            private volatile boolean closed = false;
0068
0069            private static final int O_RDONLY = 1;
0070            private static final int O_RDWR = 2;
0071            private static final int O_SYNC = 4;
0072            private static final int O_DSYNC = 8;
0073
0074            /**
0075             * Creates a random access file stream to read from, and optionally 
0076             * to write to, a file with the specified name. A new 
0077             * {@link FileDescriptor} object is created to represent the 
0078             * connection to the file.
0079             * 
0080             * <p> The <tt>mode</tt> argument specifies the access mode with which the
0081             * file is to be opened.  The permitted values and their meanings are as
0082             * specified for the <a
0083             * href="#mode"><tt>RandomAccessFile(File,String)</tt></a> constructor.
0084             *
0085             * <p>
0086             * If there is a security manager, its <code>checkRead</code> method
0087             * is called with the <code>name</code> argument
0088             * as its argument to see if read access to the file is allowed.
0089             * If the mode allows writing, the security manager's
0090             * <code>checkWrite</code> method
0091             * is also called with the <code>name</code> argument
0092             * as its argument to see if write access to the file is allowed.
0093             *
0094             * @param      name   the system-dependent filename
0095             * @param      mode   the access <a href="#mode">mode</a>
0096             * @exception  IllegalArgumentException  if the mode argument is not equal
0097             *               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
0098             *               <tt>"rwd"</tt>
0099             * @exception FileNotFoundException
0100             *            if the mode is <tt>"r"</tt> but the given string does not
0101             *            denote an existing regular file, or if the mode begins with
0102             *            <tt>"rw"</tt> but the given string does not denote an
0103             *            existing, writable regular file and a new regular file of
0104             *            that name cannot be created, or if some other error occurs
0105             *            while opening or creating the file
0106             * @exception  SecurityException         if a security manager exists and its
0107             *               <code>checkRead</code> method denies read access to the file
0108             *               or the mode is "rw" and the security manager's
0109             *               <code>checkWrite</code> method denies write access to the file
0110             * @see        java.lang.SecurityException
0111             * @see        java.lang.SecurityManager#checkRead(java.lang.String)
0112             * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
0113             * @revised 1.4
0114             * @spec JSR-51
0115             */
0116            public RandomAccessFile(String name, String mode)
0117                    throws FileNotFoundException {
0118                this (name != null ? new File(name) : null, mode);
0119            }
0120
0121            /**
0122             * Creates a random access file stream to read from, and optionally to
0123             * write to, the file specified by the {@link File} argument.  A new {@link
0124             * FileDescriptor} object is created to represent this file connection.
0125             *
0126             * <a name="mode"><p> The <tt>mode</tt> argument specifies the access mode
0127             * in which the file is to be opened.  The permitted values and their
0128             * meanings are:
0129             *
0130             * <blockquote><table summary="Access mode permitted values and meanings">
0131             * <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>
0132             * <tr><td valign="top"><tt>"r"</tt></td>
0133             *     <td> Open for reading only.  Invoking any of the <tt>write</tt>
0134             *     methods of the resulting object will cause an {@link
0135             *     java.io.IOException} to be thrown. </td></tr>
0136             * <tr><td valign="top"><tt>"rw"</tt></td>
0137             *     <td> Open for reading and writing.  If the file does not already
0138             *     exist then an attempt will be made to create it. </td></tr>
0139             * <tr><td valign="top"><tt>"rws"</tt></td>
0140             *     <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
0141             *     require that every update to the file's content or metadata be
0142             *     written synchronously to the underlying storage device.  </td></tr>
0143             * <tr><td valign="top"><tt>"rwd"&nbsp;&nbsp;</tt></td>
0144             *     <td> Open for reading and writing, as with <tt>"rw"</tt>, and also
0145             *     require that every update to the file's content be written
0146             *     synchronously to the underlying storage device. </td></tr>
0147             * </table></blockquote>
0148             *
0149             * The <tt>"rws"</tt> and <tt>"rwd"</tt> modes work much like the {@link
0150             * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of
0151             * the {@link java.nio.channels.FileChannel} class, passing arguments of
0152             * <tt>true</tt> and <tt>false</tt>, respectively, except that they always
0153             * apply to every I/O operation and are therefore often more efficient.  If
0154             * the file resides on a local storage device then when an invocation of a
0155             * method of this class returns it is guaranteed that all changes made to
0156             * the file by that invocation will have been written to that device.  This
0157             * is useful for ensuring that critical information is not lost in the
0158             * event of a system crash.  If the file does not reside on a local device
0159             * then no such guarantee is made.
0160             *
0161             * <p> The <tt>"rwd"</tt> mode can be used to reduce the number of I/O
0162             * operations performed.  Using <tt>"rwd"</tt> only requires updates to the
0163             * file's content to be written to storage; using <tt>"rws"</tt> requires
0164             * updates to both the file's content and its metadata to be written, which
0165             * generally requires at least one more low-level I/O operation.
0166             *
0167             * <p> If there is a security manager, its <code>checkRead</code> method is
0168             * called with the pathname of the <code>file</code> argument as its
0169             * argument to see if read access to the file is allowed.  If the mode
0170             * allows writing, the security manager's <code>checkWrite</code> method is
0171             * also called with the path argument to see if write access to the file is
0172             * allowed.
0173             *
0174             * @param      file   the file object
0175             * @param      mode   the access mode, as described
0176             *                    <a href="#mode">above</a>
0177             * @exception  IllegalArgumentException  if the mode argument is not equal
0178             *               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
0179             *               <tt>"rwd"</tt>
0180             * @exception FileNotFoundException
0181             *            if the mode is <tt>"r"</tt> but the given file object does
0182             *            not denote an existing regular file, or if the mode begins
0183             *            with <tt>"rw"</tt> but the given file object does not denote
0184             *            an existing, writable regular file and a new regular file of
0185             *            that name cannot be created, or if some other error occurs
0186             *            while opening or creating the file
0187             * @exception  SecurityException         if a security manager exists and its
0188             *               <code>checkRead</code> method denies read access to the file
0189             *               or the mode is "rw" and the security manager's
0190             *               <code>checkWrite</code> method denies write access to the file
0191             * @see        java.lang.SecurityManager#checkRead(java.lang.String)
0192             * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
0193             * @see        java.nio.channels.FileChannel#force(boolean)
0194             * @revised 1.4
0195             * @spec JSR-51
0196             */
0197            public RandomAccessFile(File file, String mode)
0198                    throws FileNotFoundException {
0199                String name = (file != null ? file.getPath() : null);
0200                int imode = -1;
0201                if (mode.equals("r"))
0202                    imode = O_RDONLY;
0203                else if (mode.startsWith("rw")) {
0204                    imode = O_RDWR;
0205                    rw = true;
0206                    if (mode.length() > 2) {
0207                        if (mode.equals("rws"))
0208                            imode |= O_SYNC;
0209                        else if (mode.equals("rwd"))
0210                            imode |= O_DSYNC;
0211                        else
0212                            imode = -1;
0213                    }
0214                }
0215                if (imode < 0)
0216                    throw new IllegalArgumentException("Illegal mode \"" + mode
0217                            + "\" must be one of " + "\"r\", \"rw\", \"rws\","
0218                            + " or \"rwd\"");
0219                SecurityManager security = System.getSecurityManager();
0220                if (security != null) {
0221                    security.checkRead(name);
0222                    if (rw) {
0223                        security.checkWrite(name);
0224                    }
0225                }
0226                if (name == null) {
0227                    throw new NullPointerException();
0228                }
0229                fd = new FileDescriptor();
0230                fd.incrementAndGetUseCount();
0231                open(name, imode);
0232            }
0233
0234            /**
0235             * Returns the opaque file descriptor object associated with this
0236             * stream. </p>
0237             *
0238             * @return     the file descriptor object associated with this stream.
0239             * @exception  IOException  if an I/O error occurs.
0240             * @see        java.io.FileDescriptor
0241             */
0242            public final FileDescriptor getFD() throws IOException {
0243                if (fd != null)
0244                    return fd;
0245                throw new IOException();
0246            }
0247
0248            /**
0249             * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
0250             * object associated with this file.
0251             *
0252             * <p> The {@link java.nio.channels.FileChannel#position()
0253             * </code>position<code>} of the returned channel will always be equal to
0254             * this object's file-pointer offset as returned by the {@link
0255             * #getFilePointer getFilePointer} method.  Changing this object's
0256             * file-pointer offset, whether explicitly or by reading or writing bytes,
0257             * will change the position of the channel, and vice versa.  Changing the
0258             * file's length via this object will change the length seen via the file
0259             * channel, and vice versa.
0260             *
0261             * @return  the file channel associated with this file
0262             *
0263             * @since 1.4
0264             * @spec JSR-51
0265             */
0266            public final FileChannel getChannel() {
0267                synchronized (this ) {
0268                    if (channel == null) {
0269                        channel = FileChannelImpl.open(fd, true, rw, this );
0270
0271                        /*
0272                         * FileDescriptor could be shared by FileInputStream or 
0273                         * FileOutputStream.
0274                         * Ensure that FD is GC'ed only when all the streams/channels
0275                         * are done using it.
0276                         * Increment fd's use count. Invoking the channel's close()
0277                         * method will result in decrementing the use count set for
0278                         * the channel. 
0279                         */
0280                        fd.incrementAndGetUseCount();
0281                    }
0282                    return channel;
0283                }
0284            }
0285
0286            /**
0287             * Opens a file and returns the file descriptor.  The file is
0288             * opened in read-write mode if the O_RDWR bit in <code>mode</code>
0289             * is true, else the file is opened as read-only.
0290             * If the <code>name</code> refers to a directory, an IOException
0291             * is thrown.
0292             *
0293             * @param name the name of the file
0294             * @param mode the mode flags, a combination of the O_ constants
0295             *             defined above
0296             */
0297            private native void open(String name, int mode)
0298                    throws FileNotFoundException;
0299
0300            // 'Read' primitives
0301
0302            /**
0303             * Reads a byte of data from this file. The byte is returned as an 
0304             * integer in the range 0 to 255 (<code>0x00-0x0ff</code>). This 
0305             * method blocks if no input is yet available. 
0306             * <p>
0307             * Although <code>RandomAccessFile</code> is not a subclass of 
0308             * <code>InputStream</code>, this method behaves in exactly the same 
0309             * way as the {@link InputStream#read()} method of 
0310             * <code>InputStream</code>.
0311             *
0312             * @return     the next byte of data, or <code>-1</code> if the end of the
0313             *             file has been reached.
0314             * @exception  IOException  if an I/O error occurs. Not thrown if  
0315             *                          end-of-file has been reached.
0316             */
0317            public native int read() throws IOException;
0318
0319            /**
0320             * Reads a sub array as a sequence of bytes. 
0321             * @param b the buffer into which the data is read.
0322             * @param off the start offset of the data.
0323             * @param len the number of bytes to read.
0324             * @exception IOException If an I/O error has occurred.
0325             */
0326            private native int readBytes(byte b[], int off, int len)
0327                    throws IOException;
0328
0329            /**
0330             * Reads up to <code>len</code> bytes of data from this file into an 
0331             * array of bytes. This method blocks until at least one byte of input 
0332             * is available. 
0333             * <p>
0334             * Although <code>RandomAccessFile</code> is not a subclass of 
0335             * <code>InputStream</code>, this method behaves in exactly the 
0336             * same way as the {@link InputStream#read(byte[], int, int)} method of 
0337             * <code>InputStream</code>.
0338             *
0339             * @param      b     the buffer into which the data is read.
0340             * @param      off   the start offset in array <code>b</code>
0341             *                   at which the data is written.
0342             * @param      len   the maximum number of bytes read.
0343             * @return     the total number of bytes read into the buffer, or
0344             *             <code>-1</code> if there is no more data because the end of
0345             *             the file has been reached.
0346             * @exception  IOException If the first byte cannot be read for any reason
0347             * other than end of file, or if the random access file has been closed, or if
0348             * some other I/O error occurs.
0349             * @exception  NullPointerException If <code>b</code> is <code>null</code>.
0350             * @exception  IndexOutOfBoundsException If <code>off</code> is negative, 
0351             * <code>len</code> is negative, or <code>len</code> is greater than 
0352             * <code>b.length - off</code>
0353             */
0354            public int read(byte b[], int off, int len) throws IOException {
0355                return readBytes(b, off, len);
0356            }
0357
0358            /**
0359             * Reads up to <code>b.length</code> bytes of data from this file 
0360             * into an array of bytes. This method blocks until at least one byte 
0361             * of input is available. 
0362             * <p>
0363             * Although <code>RandomAccessFile</code> is not a subclass of 
0364             * <code>InputStream</code>, this method behaves in exactly the 
0365             * same way as the {@link InputStream#read(byte[])} method of 
0366             * <code>InputStream</code>.
0367             *
0368             * @param      b   the buffer into which the data is read.
0369             * @return     the total number of bytes read into the buffer, or
0370             *             <code>-1</code> if there is no more data because the end of
0371             *             this file has been reached.
0372             * @exception  IOException If the first byte cannot be read for any reason
0373             * other than end of file, or if the random access file has been closed, or if
0374             * some other I/O error occurs.
0375             * @exception  NullPointerException If <code>b</code> is <code>null</code>.
0376             */
0377            public int read(byte b[]) throws IOException {
0378                return readBytes(b, 0, b.length);
0379            }
0380
0381            /**
0382             * Reads <code>b.length</code> bytes from this file into the byte 
0383             * array, starting at the current file pointer. This method reads 
0384             * repeatedly from the file until the requested number of bytes are 
0385             * read. This method blocks until the requested number of bytes are 
0386             * read, the end of the stream is detected, or an exception is thrown. 
0387             *
0388             * @param      b   the buffer into which the data is read.
0389             * @exception  EOFException  if this file reaches the end before reading
0390             *               all the bytes.
0391             * @exception  IOException   if an I/O error occurs.       
0392             */
0393            public final void readFully(byte b[]) throws IOException {
0394                readFully(b, 0, b.length);
0395            }
0396
0397            /**
0398             * Reads exactly <code>len</code> bytes from this file into the byte 
0399             * array, starting at the current file pointer. This method reads 
0400             * repeatedly from the file until the requested number of bytes are 
0401             * read. This method blocks until the requested number of bytes are 
0402             * read, the end of the stream is detected, or an exception is thrown. 
0403             *
0404             * @param      b     the buffer into which the data is read.
0405             * @param      off   the start offset of the data.
0406             * @param      len   the number of bytes to read.
0407             * @exception  EOFException  if this file reaches the end before reading
0408             *               all the bytes.
0409             * @exception  IOException   if an I/O error occurs.
0410             */
0411            public final void readFully(byte b[], int off, int len)
0412                    throws IOException {
0413                int n = 0;
0414                do {
0415                    int count = this .read(b, off + n, len - n);
0416                    if (count < 0)
0417                        throw new EOFException();
0418                    n += count;
0419                } while (n < len);
0420            }
0421
0422            /**
0423             * Attempts to skip over <code>n</code> bytes of input discarding the 
0424             * skipped bytes. 
0425             * <p>
0426             * 
0427             * This method may skip over some smaller number of bytes, possibly zero. 
0428             * This may result from any of a number of conditions; reaching end of 
0429             * file before <code>n</code> bytes have been skipped is only one 
0430             * possibility. This method never throws an <code>EOFException</code>. 
0431             * The actual number of bytes skipped is returned.  If <code>n</code> 
0432             * is negative, no bytes are skipped.
0433             *
0434             * @param      n   the number of bytes to be skipped.
0435             * @return     the actual number of bytes skipped.
0436             * @exception  IOException  if an I/O error occurs.
0437             */
0438            public int skipBytes(int n) throws IOException {
0439                long pos;
0440                long len;
0441                long newpos;
0442
0443                if (n <= 0) {
0444                    return 0;
0445                }
0446                pos = getFilePointer();
0447                len = length();
0448                newpos = pos + n;
0449                if (newpos > len) {
0450                    newpos = len;
0451                }
0452                seek(newpos);
0453
0454                /* return the actual number of bytes skipped */
0455                return (int) (newpos - pos);
0456            }
0457
0458            // 'Write' primitives
0459
0460            /**
0461             * Writes the specified byte to this file. The write starts at 
0462             * the current file pointer.
0463             *
0464             * @param      b   the <code>byte</code> to be written.
0465             * @exception  IOException  if an I/O error occurs.
0466             */
0467            public native void write(int b) throws IOException;
0468
0469            /**
0470             * Writes a sub array as a sequence of bytes. 
0471             * @param b the data to be written
0472
0473             * @param off the start offset in the data
0474             * @param len the number of bytes that are written
0475             * @exception IOException If an I/O error has occurred.
0476             */
0477            private native void writeBytes(byte b[], int off, int len)
0478                    throws IOException;
0479
0480            /**
0481             * Writes <code>b.length</code> bytes from the specified byte array 
0482             * to this file, starting at the current file pointer. 
0483             *
0484             * @param      b   the data.
0485             * @exception  IOException  if an I/O error occurs.
0486             */
0487            public void write(byte b[]) throws IOException {
0488                writeBytes(b, 0, b.length);
0489            }
0490
0491            /**
0492             * Writes <code>len</code> bytes from the specified byte array 
0493             * starting at offset <code>off</code> to this file. 
0494             *
0495             * @param      b     the data.
0496             * @param      off   the start offset in the data.
0497             * @param      len   the number of bytes to write.
0498             * @exception  IOException  if an I/O error occurs.
0499             */
0500            public void write(byte b[], int off, int len) throws IOException {
0501                writeBytes(b, off, len);
0502            }
0503
0504            // 'Random access' stuff
0505
0506            /**
0507             * Returns the current offset in this file. 
0508             *
0509             * @return     the offset from the beginning of the file, in bytes,
0510             *             at which the next read or write occurs.
0511             * @exception  IOException  if an I/O error occurs.
0512             */
0513            public native long getFilePointer() throws IOException;
0514
0515            /**
0516             * Sets the file-pointer offset, measured from the beginning of this 
0517             * file, at which the next read or write occurs.  The offset may be 
0518             * set beyond the end of the file. Setting the offset beyond the end 
0519             * of the file does not change the file length.  The file length will 
0520             * change only by writing after the offset has been set beyond the end 
0521             * of the file. 
0522             *
0523             * @param      pos   the offset position, measured in bytes from the 
0524             *                   beginning of the file, at which to set the file 
0525             *                   pointer.
0526             * @exception  IOException  if <code>pos</code> is less than 
0527             *                          <code>0</code> or if an I/O error occurs.
0528             */
0529            public native void seek(long pos) throws IOException;
0530
0531            /**
0532             * Returns the length of this file.
0533             *
0534             * @return     the length of this file, measured in bytes.
0535             * @exception  IOException  if an I/O error occurs.
0536             */
0537            public native long length() throws IOException;
0538
0539            /**
0540             * Sets the length of this file.
0541             *
0542             * <p> If the present length of the file as returned by the
0543             * <code>length</code> method is greater than the <code>newLength</code>
0544             * argument then the file will be truncated.  In this case, if the file
0545             * offset as returned by the <code>getFilePointer</code> method is greater
0546             * than <code>newLength</code> then after this method returns the offset
0547             * will be equal to <code>newLength</code>.
0548             *
0549             * <p> If the present length of the file as returned by the
0550             * <code>length</code> method is smaller than the <code>newLength</code>
0551             * argument then the file will be extended.  In this case, the contents of
0552             * the extended portion of the file are not defined.
0553             *
0554             * @param      newLength    The desired length of the file
0555             * @exception  IOException  If an I/O error occurs
0556             * @since      1.2
0557             */
0558            public native void setLength(long newLength) throws IOException;
0559
0560            /**
0561             * Closes this random access file stream and releases any system 
0562             * resources associated with the stream. A closed random access 
0563             * file cannot perform input or output operations and cannot be 
0564             * reopened.
0565             *
0566             * <p> If this file has an associated channel then the channel is closed
0567             * as well.
0568             *
0569             * @exception  IOException  if an I/O error occurs.
0570             *
0571             * @revised 1.4
0572             * @spec JSR-51
0573             */
0574            public void close() throws IOException {
0575                synchronized (closeLock) {
0576                    if (closed) {
0577                        return;
0578                    }
0579                    closed = true;
0580                }
0581                if (channel != null) {
0582                    /*
0583                     * Decrement FD use count associated with the channel. The FD use
0584                     * count is incremented whenever a new channel is obtained from
0585                     * this stream.
0586                     */
0587                    fd.decrementAndGetUseCount();
0588                    channel.close();
0589                }
0590
0591                /*
0592                 * Decrement FD use count associated with this stream.
0593                 * The count got incremented by FileDescriptor during its construction.
0594                 */
0595                fd.decrementAndGetUseCount();
0596                close0();
0597            }
0598
0599            //
0600            //  Some "reading/writing Java data types" methods stolen from
0601            //  DataInputStream and DataOutputStream.
0602            //
0603
0604            /**
0605             * Reads a <code>boolean</code> from this file. This method reads a 
0606             * single byte from the file, starting at the current file pointer. 
0607             * A value of <code>0</code> represents 
0608             * <code>false</code>. Any other value represents <code>true</code>. 
0609             * This method blocks until the byte is read, the end of the stream 
0610             * is detected, or an exception is thrown. 
0611             *
0612             * @return     the <code>boolean</code> value read.
0613             * @exception  EOFException  if this file has reached the end.
0614             * @exception  IOException   if an I/O error occurs.
0615             */
0616            public final boolean readBoolean() throws IOException {
0617                int ch = this .read();
0618                if (ch < 0)
0619                    throw new EOFException();
0620                return (ch != 0);
0621            }
0622
0623            /**
0624             * Reads a signed eight-bit value from this file. This method reads a 
0625             * byte from the file, starting from the current file pointer. 
0626             * If the byte read is <code>b</code>, where 
0627             * <code>0&nbsp;&lt;=&nbsp;b&nbsp;&lt;=&nbsp;255</code>, 
0628             * then the result is:
0629             * <blockquote><pre>
0630             *     (byte)(b)
0631             * </pre></blockquote>
0632             * <p>
0633             * This method blocks until the byte is read, the end of the stream 
0634             * is detected, or an exception is thrown. 
0635             *
0636             * @return     the next byte of this file as a signed eight-bit
0637             *             <code>byte</code>.
0638             * @exception  EOFException  if this file has reached the end.
0639             * @exception  IOException   if an I/O error occurs.
0640             */
0641            public final byte readByte() throws IOException {
0642                int ch = this .read();
0643                if (ch < 0)
0644                    throw new EOFException();
0645                return (byte) (ch);
0646            }
0647
0648            /**
0649             * Reads an unsigned eight-bit number from this file. This method reads 
0650             * a byte from this file, starting at the current file pointer, 
0651             * and returns that byte. 
0652             * <p>
0653             * This method blocks until the byte is read, the end of the stream 
0654             * is detected, or an exception is thrown. 
0655             *
0656             * @return     the next byte of this file, interpreted as an unsigned
0657             *             eight-bit number.
0658             * @exception  EOFException  if this file has reached the end.
0659             * @exception  IOException   if an I/O error occurs.
0660             */
0661            public final int readUnsignedByte() throws IOException {
0662                int ch = this .read();
0663                if (ch < 0)
0664                    throw new EOFException();
0665                return ch;
0666            }
0667
0668            /**
0669             * Reads a signed 16-bit number from this file. The method reads two 
0670             * bytes from this file, starting at the current file pointer. 
0671             * If the two bytes read, in order, are 
0672             * <code>b1</code> and <code>b2</code>, where each of the two values is 
0673             * between <code>0</code> and <code>255</code>, inclusive, then the 
0674             * result is equal to:
0675             * <blockquote><pre>
0676             *     (short)((b1 &lt;&lt; 8) | b2)
0677             * </pre></blockquote>
0678             * <p>
0679             * This method blocks until the two bytes are read, the end of the 
0680             * stream is detected, or an exception is thrown. 
0681             *
0682             * @return     the next two bytes of this file, interpreted as a signed
0683             *             16-bit number.
0684             * @exception  EOFException  if this file reaches the end before reading
0685             *               two bytes.
0686             * @exception  IOException   if an I/O error occurs.
0687             */
0688            public final short readShort() throws IOException {
0689                int ch1 = this .read();
0690                int ch2 = this .read();
0691                if ((ch1 | ch2) < 0)
0692                    throw new EOFException();
0693                return (short) ((ch1 << 8) + (ch2 << 0));
0694            }
0695
0696            /**
0697             * Reads an unsigned 16-bit number from this file. This method reads 
0698             * two bytes from the file, starting at the current file pointer. 
0699             * If the bytes read, in order, are 
0700             * <code>b1</code> and <code>b2</code>, where 
0701             * <code>0&nbsp;&lt;=&nbsp;b1, b2&nbsp;&lt;=&nbsp;255</code>, 
0702             * then the result is equal to:
0703             * <blockquote><pre>
0704             *     (b1 &lt;&lt; 8) | b2
0705             * </pre></blockquote>
0706             * <p>
0707             * This method blocks until the two bytes are read, the end of the 
0708             * stream is detected, or an exception is thrown. 
0709             *
0710             * @return     the next two bytes of this file, interpreted as an unsigned
0711             *             16-bit integer.
0712             * @exception  EOFException  if this file reaches the end before reading
0713             *               two bytes.
0714             * @exception  IOException   if an I/O error occurs.
0715             */
0716            public final int readUnsignedShort() throws IOException {
0717                int ch1 = this .read();
0718                int ch2 = this .read();
0719                if ((ch1 | ch2) < 0)
0720                    throw new EOFException();
0721                return (ch1 << 8) + (ch2 << 0);
0722            }
0723
0724            /**
0725             * Reads a character from this file. This method reads two
0726             * bytes from the file, starting at the current file pointer. 
0727             * If the bytes read, in order, are 
0728             * <code>b1</code> and <code>b2</code>, where 
0729             * <code>0&nbsp;&lt;=&nbsp;b1,&nbsp;b2&nbsp;&lt;=&nbsp;255</code>, 
0730             * then the result is equal to:
0731             * <blockquote><pre>
0732             *     (char)((b1 &lt;&lt; 8) | b2)
0733             * </pre></blockquote>
0734             * <p>
0735             * This method blocks until the two bytes are read, the end of the 
0736             * stream is detected, or an exception is thrown. 
0737             *
0738             * @return     the next two bytes of this file, interpreted as a
0739             *			<code>char</code>.
0740             * @exception  EOFException  if this file reaches the end before reading
0741             *               two bytes.
0742             * @exception  IOException   if an I/O error occurs.
0743             */
0744            public final char readChar() throws IOException {
0745                int ch1 = this .read();
0746                int ch2 = this .read();
0747                if ((ch1 | ch2) < 0)
0748                    throw new EOFException();
0749                return (char) ((ch1 << 8) + (ch2 << 0));
0750            }
0751
0752            /**
0753             * Reads a signed 32-bit integer from this file. This method reads 4 
0754             * bytes from the file, starting at the current file pointer. 
0755             * If the bytes read, in order, are <code>b1</code>,
0756             * <code>b2</code>, <code>b3</code>, and <code>b4</code>, where 
0757             * <code>0&nbsp;&lt;=&nbsp;b1, b2, b3, b4&nbsp;&lt;=&nbsp;255</code>, 
0758             * then the result is equal to:
0759             * <blockquote><pre>
0760             *     (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4
0761             * </pre></blockquote>
0762             * <p>
0763             * This method blocks until the four bytes are read, the end of the 
0764             * stream is detected, or an exception is thrown. 
0765             *
0766             * @return     the next four bytes of this file, interpreted as an
0767             *             <code>int</code>.
0768             * @exception  EOFException  if this file reaches the end before reading
0769             *               four bytes.
0770             * @exception  IOException   if an I/O error occurs.
0771             */
0772            public final int readInt() throws IOException {
0773                int ch1 = this .read();
0774                int ch2 = this .read();
0775                int ch3 = this .read();
0776                int ch4 = this .read();
0777                if ((ch1 | ch2 | ch3 | ch4) < 0)
0778                    throw new EOFException();
0779                return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
0780            }
0781
0782            /**
0783             * Reads a signed 64-bit integer from this file. This method reads eight
0784             * bytes from the file, starting at the current file pointer. 
0785             * If the bytes read, in order, are 
0786             * <code>b1</code>, <code>b2</code>, <code>b3</code>, 
0787             * <code>b4</code>, <code>b5</code>, <code>b6</code>, 
0788             * <code>b7</code>, and <code>b8,</code> where:
0789             * <blockquote><pre>
0790             *     0 &lt;= b1, b2, b3, b4, b5, b6, b7, b8 &lt;=255,
0791             * </pre></blockquote>
0792             * <p>
0793             * then the result is equal to:
0794             * <p><blockquote><pre>
0795             *     ((long)b1 &lt;&lt; 56) + ((long)b2 &lt;&lt; 48)
0796             *     + ((long)b3 &lt;&lt; 40) + ((long)b4 &lt;&lt; 32)
0797             *     + ((long)b5 &lt;&lt; 24) + ((long)b6 &lt;&lt; 16)
0798             *     + ((long)b7 &lt;&lt; 8) + b8
0799             * </pre></blockquote>
0800             * <p>
0801             * This method blocks until the eight bytes are read, the end of the 
0802             * stream is detected, or an exception is thrown. 
0803             *
0804             * @return     the next eight bytes of this file, interpreted as a
0805             *             <code>long</code>.
0806             * @exception  EOFException  if this file reaches the end before reading
0807             *               eight bytes.
0808             * @exception  IOException   if an I/O error occurs.
0809             */
0810            public final long readLong() throws IOException {
0811                return ((long) (readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
0812            }
0813
0814            /**
0815             * Reads a <code>float</code> from this file. This method reads an 
0816             * <code>int</code> value, starting at the current file pointer, 
0817             * as if by the <code>readInt</code> method 
0818             * and then converts that <code>int</code> to a <code>float</code> 
0819             * using the <code>intBitsToFloat</code> method in class 
0820             * <code>Float</code>. 
0821             * <p>
0822             * This method blocks until the four bytes are read, the end of the 
0823             * stream is detected, or an exception is thrown. 
0824             *
0825             * @return     the next four bytes of this file, interpreted as a
0826             *             <code>float</code>.
0827             * @exception  EOFException  if this file reaches the end before reading
0828             *             four bytes.
0829             * @exception  IOException   if an I/O error occurs.
0830             * @see        java.io.RandomAccessFile#readInt()
0831             * @see        java.lang.Float#intBitsToFloat(int)
0832             */
0833            public final float readFloat() throws IOException {
0834                return Float.intBitsToFloat(readInt());
0835            }
0836
0837            /**
0838             * Reads a <code>double</code> from this file. This method reads a 
0839             * <code>long</code> value, starting at the current file pointer, 
0840             * as if by the <code>readLong</code> method 
0841             * and then converts that <code>long</code> to a <code>double</code> 
0842             * using the <code>longBitsToDouble</code> method in 
0843             * class <code>Double</code>.
0844             * <p>
0845             * This method blocks until the eight bytes are read, the end of the 
0846             * stream is detected, or an exception is thrown. 
0847             *
0848             * @return     the next eight bytes of this file, interpreted as a
0849             *             <code>double</code>.
0850             * @exception  EOFException  if this file reaches the end before reading
0851             *             eight bytes.
0852             * @exception  IOException   if an I/O error occurs.
0853             * @see        java.io.RandomAccessFile#readLong()
0854             * @see        java.lang.Double#longBitsToDouble(long)
0855             */
0856            public final double readDouble() throws IOException {
0857                return Double.longBitsToDouble(readLong());
0858            }
0859
0860            /**
0861             * Reads the next line of text from this file.  This method successively
0862             * reads bytes from the file, starting at the current file pointer, 
0863             * until it reaches a line terminator or the end
0864             * of the file.  Each byte is converted into a character by taking the
0865             * byte's value for the lower eight bits of the character and setting the
0866             * high eight bits of the character to zero.  This method does not,
0867             * therefore, support the full Unicode character set.
0868             *
0869             * <p> A line of text is terminated by a carriage-return character
0870             * (<code>'&#92;r'</code>), a newline character (<code>'&#92;n'</code>), a
0871             * carriage-return character immediately followed by a newline character,
0872             * or the end of the file.  Line-terminating characters are discarded and
0873             * are not included as part of the string returned.
0874             *
0875             * <p> This method blocks until a newline character is read, a carriage
0876             * return and the byte following it are read (to see if it is a newline),
0877             * the end of the file is reached, or an exception is thrown.
0878             *
0879             * @return     the next line of text from this file, or null if end
0880             *             of file is encountered before even one byte is read.
0881             * @exception  IOException  if an I/O error occurs.
0882             */
0883
0884            public final String readLine() throws IOException {
0885                StringBuffer input = new StringBuffer();
0886                int c = -1;
0887                boolean eol = false;
0888
0889                while (!eol) {
0890                    switch (c = read()) {
0891                    case -1:
0892                    case '\n':
0893                        eol = true;
0894                        break;
0895                    case '\r':
0896                        eol = true;
0897                        long cur = getFilePointer();
0898                        if ((read()) != '\n') {
0899                            seek(cur);
0900                        }
0901                        break;
0902                    default:
0903                        input.append((char) c);
0904                        break;
0905                    }
0906                }
0907
0908                if ((c == -1) && (input.length() == 0)) {
0909                    return null;
0910                }
0911                return input.toString();
0912            }
0913
0914            /**
0915             * Reads in a string from this file. The string has been encoded 
0916             * using a
0917             * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
0918             * format. 
0919             * <p>
0920             * The first two bytes are read, starting from the current file 
0921             * pointer, as if by 
0922             * <code>readUnsignedShort</code>. This value gives the number of 
0923             * following bytes that are in the encoded string, not
0924             * the length of the resulting string. The following bytes are then 
0925             * interpreted as bytes encoding characters in the modified UTF-8 format 
0926             * and are converted into characters. 
0927             * <p>
0928             * This method blocks until all the bytes are read, the end of the 
0929             * stream is detected, or an exception is thrown. 
0930             *
0931             * @return     a Unicode string.
0932             * @exception  EOFException            if this file reaches the end before
0933             *               reading all the bytes.
0934             * @exception  IOException             if an I/O error occurs.
0935             * @exception  UTFDataFormatException  if the bytes do not represent 
0936             *               valid modified UTF-8 encoding of a Unicode string.
0937             * @see        java.io.RandomAccessFile#readUnsignedShort()
0938             */
0939            public final String readUTF() throws IOException {
0940                return DataInputStream.readUTF(this );
0941            }
0942
0943            /**
0944             * Writes a <code>boolean</code> to the file as a one-byte value. The 
0945             * value <code>true</code> is written out as the value 
0946             * <code>(byte)1</code>; the value <code>false</code> is written out 
0947             * as the value <code>(byte)0</code>. The write starts at 
0948             * the current position of the file pointer.
0949             *
0950             * @param      v   a <code>boolean</code> value to be written.
0951             * @exception  IOException  if an I/O error occurs.
0952             */
0953            public final void writeBoolean(boolean v) throws IOException {
0954                write(v ? 1 : 0);
0955                //written++;
0956            }
0957
0958            /**
0959             * Writes a <code>byte</code> to the file as a one-byte value. The 
0960             * write starts at the current position of the file pointer.
0961             *
0962             * @param      v   a <code>byte</code> value to be written.
0963             * @exception  IOException  if an I/O error occurs.
0964             */
0965            public final void writeByte(int v) throws IOException {
0966                write(v);
0967                //written++;
0968            }
0969
0970            /**
0971             * Writes a <code>short</code> to the file as two bytes, high byte first. 
0972             * The write starts at the current position of the file pointer.
0973             *
0974             * @param      v   a <code>short</code> to be written.
0975             * @exception  IOException  if an I/O error occurs.
0976             */
0977            public final void writeShort(int v) throws IOException {
0978                write((v >>> 8) & 0xFF);
0979                write((v >>> 0) & 0xFF);
0980                //written += 2;
0981            }
0982
0983            /**
0984             * Writes a <code>char</code> to the file as a two-byte value, high
0985             * byte first. The write starts at the current position of the 
0986             * file pointer.
0987             *
0988             * @param      v   a <code>char</code> value to be written.
0989             * @exception  IOException  if an I/O error occurs.
0990             */
0991            public final void writeChar(int v) throws IOException {
0992                write((v >>> 8) & 0xFF);
0993                write((v >>> 0) & 0xFF);
0994                //written += 2;
0995            }
0996
0997            /**
0998             * Writes an <code>int</code> to the file as four bytes, high byte first. 
0999             * The write starts at the current position of the file pointer.
1000             *
1001             * @param      v   an <code>int</code> to be written.
1002             * @exception  IOException  if an I/O error occurs.
1003             */
1004            public final void writeInt(int v) throws IOException {
1005                write((v >>> 24) & 0xFF);
1006                write((v >>> 16) & 0xFF);
1007                write((v >>> 8) & 0xFF);
1008                write((v >>> 0) & 0xFF);
1009                //written += 4;
1010            }
1011
1012            /**
1013             * Writes a <code>long</code> to the file as eight bytes, high byte first. 
1014             * The write starts at the current position of the file pointer.
1015             *
1016             * @param      v   a <code>long</code> to be written.
1017             * @exception  IOException  if an I/O error occurs.
1018             */
1019            public final void writeLong(long v) throws IOException {
1020                write((int) (v >>> 56) & 0xFF);
1021                write((int) (v >>> 48) & 0xFF);
1022                write((int) (v >>> 40) & 0xFF);
1023                write((int) (v >>> 32) & 0xFF);
1024                write((int) (v >>> 24) & 0xFF);
1025                write((int) (v >>> 16) & 0xFF);
1026                write((int) (v >>> 8) & 0xFF);
1027                write((int) (v >>> 0) & 0xFF);
1028                //written += 8;
1029            }
1030
1031            /**
1032             * Converts the float argument to an <code>int</code> using the 
1033             * <code>floatToIntBits</code> method in class <code>Float</code>, 
1034             * and then writes that <code>int</code> value to the file as a 
1035             * four-byte quantity, high byte first. The write starts at the 
1036             * current position of the file pointer.
1037             *
1038             * @param      v   a <code>float</code> value to be written.
1039             * @exception  IOException  if an I/O error occurs.
1040             * @see        java.lang.Float#floatToIntBits(float)
1041             */
1042            public final void writeFloat(float v) throws IOException {
1043                writeInt(Float.floatToIntBits(v));
1044            }
1045
1046            /**
1047             * Converts the double argument to a <code>long</code> using the 
1048             * <code>doubleToLongBits</code> method in class <code>Double</code>, 
1049             * and then writes that <code>long</code> value to the file as an 
1050             * eight-byte quantity, high byte first. The write starts at the current 
1051             * position of the file pointer.
1052             *
1053             * @param      v   a <code>double</code> value to be written.
1054             * @exception  IOException  if an I/O error occurs.
1055             * @see        java.lang.Double#doubleToLongBits(double)
1056             */
1057            public final void writeDouble(double v) throws IOException {
1058                writeLong(Double.doubleToLongBits(v));
1059            }
1060
1061            /**
1062             * Writes the string to the file as a sequence of bytes. Each 
1063             * character in the string is written out, in sequence, by discarding 
1064             * its high eight bits. The write starts at the current position of 
1065             * the file pointer.
1066             *
1067             * @param      s   a string of bytes to be written.
1068             * @exception  IOException  if an I/O error occurs.
1069             */
1070            public final void writeBytes(String s) throws IOException {
1071                int len = s.length();
1072                byte[] b = new byte[len];
1073                s.getBytes(0, len, b, 0);
1074                writeBytes(b, 0, len);
1075            }
1076
1077            /**
1078             * Writes a string to the file as a sequence of characters. Each 
1079             * character is written to the data output stream as if by the 
1080             * <code>writeChar</code> method. The write starts at the current 
1081             * position of the file pointer.
1082             *
1083             * @param      s   a <code>String</code> value to be written.
1084             * @exception  IOException  if an I/O error occurs.
1085             * @see        java.io.RandomAccessFile#writeChar(int)
1086             */
1087            public final void writeChars(String s) throws IOException {
1088                int clen = s.length();
1089                int blen = 2 * clen;
1090                byte[] b = new byte[blen];
1091                char[] c = new char[clen];
1092                s.getChars(0, clen, c, 0);
1093                for (int i = 0, j = 0; i < clen; i++) {
1094                    b[j++] = (byte) (c[i] >>> 8);
1095                    b[j++] = (byte) (c[i] >>> 0);
1096                }
1097                writeBytes(b, 0, blen);
1098            }
1099
1100            /**
1101             * Writes a string to the file using
1102             * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1103             * encoding in a machine-independent manner. 
1104             * <p>
1105             * First, two bytes are written to the file, starting at the 
1106             * current file pointer, as if by the 
1107             * <code>writeShort</code> method giving the number of bytes to 
1108             * follow. This value is the number of bytes actually written out, 
1109             * not the length of the string. Following the length, each character 
1110             * of the string is output, in sequence, using the modified UTF-8 encoding 
1111             * for each character. 
1112             *
1113             * @param      str   a string to be written.
1114             * @exception  IOException  if an I/O error occurs.
1115             */
1116            public final void writeUTF(String str) throws IOException {
1117                DataOutputStream.writeUTF(str, this );
1118            }
1119
1120            private static native void initIDs();
1121
1122            private native void close0() throws IOException;
1123
1124            static {
1125                initIDs();
1126            }
1127        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.