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