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