1 /*
   2  * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.nio.channels.FileChannel;
  29 import sun.nio.ch.FileChannelImpl;
  30 import sun.misc.IoTrace;
  31 
  32 
  33 /**
  34  * A <code>FileInputStream</code> obtains input bytes
  35  * from a file in a file system. What files
  36  * are  available depends on the host environment.
  37  *
  38  * <p><code>FileInputStream</code> is meant for reading streams of raw bytes
  39  * such as image data. For reading streams of characters, consider using
  40  * <code>FileReader</code>.
  41  *
  42  * @author  Arthur van Hoff
  43  * @see     java.io.File
  44  * @see     java.io.FileDescriptor
  45  * @see     java.io.FileOutputStream
  46  * @see     java.nio.file.Files#newInputStream
  47  * @since   JDK1.0
  48  */
  49 public
  50 class FileInputStream extends InputStream
  51 {
  52     /* File Descriptor - handle to the open file */
  53     private final FileDescriptor fd;
  54 
  55     /* The path of the referenced file (null if there is no file) */
  56     private final String path;
  57 
  58     private FileChannel channel = null;
  59 
  60     private final Object closeLock = new Object();
  61     private volatile boolean closed = false;
  62 
  63     /**
  64      * Creates a <code>FileInputStream</code> by
  65      * opening a connection to an actual file,
  66      * the file named by the path name <code>name</code>
  67      * in the file system.  A new <code>FileDescriptor</code>
  68      * object is created to represent this file
  69      * connection.
  70      * <p>
  71      * First, if there is a security
  72      * manager, its <code>checkRead</code> method
  73      * is called with the <code>name</code> argument
  74      * as its argument.
  75      * <p>
  76      * If the named file does not exist, is a directory rather than a regular
  77      * file, or for some other reason cannot be opened for reading then a
  78      * <code>FileNotFoundException</code> is thrown.
  79      *
  80      * @param      name   the system-dependent file name.
  81      * @exception  FileNotFoundException  if the file does not exist,
  82      *                   is a directory rather than a regular file,
  83      *                   or for some other reason cannot be opened for
  84      *                   reading.
  85      * @exception  SecurityException      if a security manager exists and its
  86      *               <code>checkRead</code> method denies read access
  87      *               to the file.
  88      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
  89      */
  90     public FileInputStream(String name) throws FileNotFoundException {
  91         this(name != null ? new File(name) : null);
  92     }
  93 
  94     /**
  95      * Creates a <code>FileInputStream</code> by
  96      * opening a connection to an actual file,
  97      * the file named by the <code>File</code>
  98      * object <code>file</code> in the file system.
  99      * A new <code>FileDescriptor</code> object
 100      * is created to represent this file connection.
 101      * <p>
 102      * First, if there is a security manager,
 103      * its <code>checkRead</code> method  is called
 104      * with the path represented by the <code>file</code>
 105      * argument as its argument.
 106      * <p>
 107      * If the named file does not exist, is a directory rather than a regular
 108      * file, or for some other reason cannot be opened for reading then a
 109      * <code>FileNotFoundException</code> is thrown.
 110      *
 111      * @param      file   the file to be opened for reading.
 112      * @exception  FileNotFoundException  if the file does not exist,
 113      *                   is a directory rather than a regular file,
 114      *                   or for some other reason cannot be opened for
 115      *                   reading.
 116      * @exception  SecurityException      if a security manager exists and its
 117      *               <code>checkRead</code> method denies read access to the file.
 118      * @see        java.io.File#getPath()
 119      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
 120      */
 121     public FileInputStream(File file) throws FileNotFoundException {
 122         String name = (file != null ? file.getPath() : null);
 123         SecurityManager security = System.getSecurityManager();
 124         if (security != null) {
 125             security.checkRead(name);
 126         }
 127         if (name == null) {
 128             throw new NullPointerException();
 129         }
 130         fd = new FileDescriptor();
 131         fd.attach(this);
 132         this.path = name;
 133         open(name);
 134     }
 135 
 136     /**
 137      * Creates a <code>FileInputStream</code> by using the file descriptor
 138      * <code>fdObj</code>, which represents an existing connection to an
 139      * actual file in the file system.
 140      * <p>
 141      * If there is a security manager, its <code>checkRead</code> method is
 142      * called with the file descriptor <code>fdObj</code> as its argument to
 143      * see if it's ok to read the file descriptor. If read access is denied
 144      * to the file descriptor a <code>SecurityException</code> is thrown.
 145      * <p>
 146      * If <code>fdObj</code> is null then a <code>NullPointerException</code>
 147      * is thrown.
 148      * <p>
 149      * This constructor does not throw an exception if <code>fdObj</code>
 150      * is {@link java.io.FileDescriptor#valid() invalid}.
 151      * However, if the methods are invoked on the resulting stream to attempt
 152      * I/O on the stream, an <code>IOException</code> is thrown.
 153      *
 154      * @param      fdObj   the file descriptor to be opened for reading.
 155      * @throws     SecurityException      if a security manager exists and its
 156      *                 <code>checkRead</code> method denies read access to the
 157      *                 file descriptor.
 158      * @see        SecurityManager#checkRead(java.io.FileDescriptor)
 159      */
 160     public FileInputStream(FileDescriptor fdObj) {
 161         SecurityManager security = System.getSecurityManager();
 162         if (fdObj == null) {
 163             throw new NullPointerException();
 164         }
 165         if (security != null) {
 166             security.checkRead(fdObj);
 167         }
 168         fd = fdObj;
 169         path = null;
 170 
 171         /*
 172          * FileDescriptor is being shared by streams.
 173          * Register this stream with FileDescriptor tracker.
 174          */
 175         fd.attach(this);
 176     }
 177 
 178     /**
 179      * Opens the specified file for reading.
 180      * @param name the name of the file
 181      */
 182     private native void open(String name) throws FileNotFoundException;
 183 
 184     /**
 185      * Reads a byte of data from this input stream. This method blocks
 186      * if no input is yet available.
 187      *
 188      * @return     the next byte of data, or <code>-1</code> if the end of the
 189      *             file is reached.
 190      * @exception  IOException  if an I/O error occurs.
 191      */
 192     public int read() throws IOException {
 193         Object traceHandle = IoTrace.fileReadBegin(path);
 194         int b = read0();
 195         IoTrace.fileReadEnd(traceHandle, b == -1 ? -1 : 1);
 196         return b;
 197     }
 198 
 199     private native int read0() throws IOException;
 200 
 201     /**
 202      * Reads a subarray as a sequence of bytes.
 203      * @param b the data to be written
 204      * @param off the start offset in the data
 205      * @param len the number of bytes that are written
 206      * @exception IOException If an I/O error has occurred.
 207      */
 208     private native int readBytes(byte b[], int off, int len) throws IOException;
 209 
 210     /**
 211      * Reads up to <code>b.length</code> bytes of data from this input
 212      * stream into an array of bytes. This method blocks until some input
 213      * is available.
 214      *
 215      * @param      b   the buffer into which the data is read.
 216      * @return     the total number of bytes read into the buffer, or
 217      *             <code>-1</code> if there is no more data because the end of
 218      *             the file has been reached.
 219      * @exception  IOException  if an I/O error occurs.
 220      */
 221     public int read(byte b[]) throws IOException {
 222         Object traceHandle = IoTrace.fileReadBegin(path);
 223         int bytesRead = readBytes(b, 0, b.length);
 224         IoTrace.fileReadEnd(traceHandle, bytesRead);
 225         return bytesRead;
 226     }
 227 
 228     /**
 229      * Reads up to <code>len</code> bytes of data from this input stream
 230      * into an array of bytes. If <code>len</code> is not zero, the method
 231      * blocks until some input is available; otherwise, no
 232      * bytes are read and <code>0</code> is returned.
 233      *
 234      * @param      b     the buffer into which the data is read.
 235      * @param      off   the start offset in the destination array <code>b</code>
 236      * @param      len   the maximum number of bytes read.
 237      * @return     the total number of bytes read into the buffer, or
 238      *             <code>-1</code> if there is no more data because the end of
 239      *             the file has been reached.
 240      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 241      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
 242      * <code>len</code> is negative, or <code>len</code> is greater than
 243      * <code>b.length - off</code>
 244      * @exception  IOException  if an I/O error occurs.
 245      */
 246     public int read(byte b[], int off, int len) throws IOException {
 247         Object traceHandle = IoTrace.fileReadBegin(path);
 248         int bytesRead = readBytes(b, off, len);
 249         IoTrace.fileReadEnd(traceHandle, bytesRead);
 250         return bytesRead;
 251     }
 252 
 253     /**
 254      * Skips over and discards <code>n</code> bytes of data from the
 255      * input stream.
 256      *
 257      * <p>The <code>skip</code> method may, for a variety of
 258      * reasons, end up skipping over some smaller number of bytes,
 259      * possibly <code>0</code>. If <code>n</code> is negative, an
 260      * <code>IOException</code> is thrown, even though the <code>skip</code>
 261      * method of the {@link InputStream} superclass does nothing in this case.
 262      * The actual number of bytes skipped is returned.
 263      *
 264      * <p>This method may skip more bytes than are remaining in the backing
 265      * file. This produces no exception and the number of bytes skipped
 266      * may include some number of bytes that were beyond the EOF of the
 267      * backing file. Attempting to read from the stream after skipping past
 268      * the end will result in -1 indicating the end of the file.
 269      *
 270      * @param      n   the number of bytes to be skipped.
 271      * @return     the actual number of bytes skipped.
 272      * @exception  IOException  if n is negative, if the stream does not
 273      *             support seek, or if an I/O error occurs.
 274      */
 275     public native long skip(long n) throws IOException;
 276 
 277     /**
 278      * Returns an estimate of the number of remaining bytes that can be read (or
 279      * skipped over) from this input stream without blocking by the next
 280      * invocation of a method for this input stream. The next invocation might be
 281      * the same thread or another thread.  A single read or skip of this
 282      * many bytes will not block, but may read or skip fewer bytes.
 283      *
 284      * <p> In some cases, a non-blocking read (or skip) may appear to be
 285      * blocked when it is merely slow, for example when reading large
 286      * files over slow networks.
 287      *
 288      * @return     an estimate of the number of remaining bytes that can be read
 289      *             (or skipped over) from this input stream without blocking.
 290      * @exception  IOException  if this file input stream has been closed by calling
 291      *             {@code close} or an I/O error occurs.
 292      */
 293     public native int available() throws IOException;
 294 
 295     /**
 296      * Closes this file input stream and releases any system resources
 297      * associated with the stream.
 298      *
 299      * <p> If this stream has an associated channel then the channel is closed
 300      * as well.
 301      *
 302      * @exception  IOException  if an I/O error occurs.
 303      *
 304      * @revised 1.4
 305      * @spec JSR-51
 306      */
 307     public void close() throws IOException {
 308         synchronized (closeLock) {
 309             if (closed) {
 310                 return;
 311             }
 312             closed = true;
 313         }
 314         if (channel != null) {
 315            channel.close();
 316         }
 317 
 318         fd.closeAll(new Closeable() {
 319             public void close() throws IOException {
 320                close0();
 321            }
 322         });
 323     }
 324 
 325     /**
 326      * Returns the <code>FileDescriptor</code>
 327      * object  that represents the connection to
 328      * the actual file in the file system being
 329      * used by this <code>FileInputStream</code>.
 330      *
 331      * @return     the file descriptor object associated with this stream.
 332      * @exception  IOException  if an I/O error occurs.
 333      * @see        java.io.FileDescriptor
 334      */
 335     public final FileDescriptor getFD() throws IOException {
 336         if (fd != null) {
 337             return fd;
 338         }
 339         throw new IOException();
 340     }
 341 
 342     /**
 343      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
 344      * object associated with this file input stream.
 345      *
 346      * <p> The initial {@link java.nio.channels.FileChannel#position()
 347      * </code>position<code>} of the returned channel will be equal to the
 348      * number of bytes read from the file so far.  Reading bytes from this
 349      * stream will increment the channel's position.  Changing the channel's
 350      * position, either explicitly or by reading, will change this stream's
 351      * file position.
 352      *
 353      * @return  the file channel associated with this file input stream
 354      *
 355      * @since 1.4
 356      * @spec JSR-51
 357      */
 358     public FileChannel getChannel() {
 359         synchronized (this) {
 360             if (channel == null) {
 361                 channel = FileChannelImpl.open(fd, path, true, false, this);
 362             }
 363             return channel;
 364         }
 365     }
 366 
 367     private static native void initIDs();
 368 
 369     private native void close0() throws IOException;
 370 
 371     static {
 372         initIDs();
 373     }
 374 
 375     /**
 376      * Ensures that the <code>close</code> method of this file input stream is
 377      * called when there are no more references to it.
 378      *
 379      * @exception  IOException  if an I/O error occurs.
 380      * @see        java.io.FileInputStream#close()
 381      */
 382     protected void finalize() throws IOException {
 383         if ((fd != null) &&  (fd != FileDescriptor.in)) {
 384             /* if fd is shared, the references in FileDescriptor
 385              * will ensure that finalizer is only called when
 386              * safe to do so. All references using the fd have
 387              * become unreachable. We can call close()
 388              */
 389             close();
 390         }
 391     }
 392 }