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