View Javadoc
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 native int read() throws IOException;
190 
191     /**
192      * Reads a subarray as a sequence of bytes.
193      * @param b the data to be written
194      * @param off the start offset in the data
195      * @param len the number of bytes that are written
196      * @exception IOException If an I/O error has occurred.
197      */
198     private native int readBytes(byte b[], int off, int len) throws IOException;
199 
200     /**
201      * Reads up to <code>b.length</code> bytes of data from this input
202      * stream into an array of bytes. This method blocks until some input
203      * is available.
204      *
205      * @param      b   the buffer into which the data is read.
206      * @return     the total number of bytes read into the buffer, or
207      *             <code>-1</code> if there is no more data because the end of
208      *             the file has been reached.
209      * @exception  IOException  if an I/O error occurs.
210      */
211     public int read(byte b[]) throws IOException {
212         return readBytes(b, 0, b.length);
213     }
214 
215     /**
216      * Reads up to <code>len</code> bytes of data from this input stream
217      * into an array of bytes. If <code>len</code> is not zero, the method
218      * blocks until some input is available; otherwise, no
219      * bytes are read and <code>0</code> is returned.
220      *
221      * @param      b     the buffer into which the data is read.
222      * @param      off   the start offset in the destination array <code>b</code>
223      * @param      len   the maximum number of bytes read.
224      * @return     the total number of bytes read into the buffer, or
225      *             <code>-1</code> if there is no more data because the end of
226      *             the file has been reached.
227      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
228      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
229      * <code>len</code> is negative, or <code>len</code> is greater than
230      * <code>b.length - off</code>
231      * @exception  IOException  if an I/O error occurs.
232      */
233     public int read(byte b[], int off, int len) throws IOException {
234         return readBytes(b, off, len);
235     }
236 
237     /**
238      * Skips over and discards <code>n</code> bytes of data from the
239      * input stream.
240      *
241      * <p>The <code>skip</code> method may, for a variety of
242      * reasons, end up skipping over some smaller number of bytes,
243      * possibly <code>0</code>. If <code>n</code> is negative, the method
244      * will try to skip backwards. In case the backing file does not support
245      * backward skip at its current position, an <code>IOException</code> is
246      * thrown. The actual number of bytes skipped is returned. If it skips
247      * forwards, it returns a positive value. If it skips backwards, it
248      * returns a negative value.
249      *
250      * <p>This method may skip more bytes than what are remaining in the
251      * backing file. This produces no exception and the number of bytes skipped
252      * may include some number of bytes that were beyond the EOF of the
253      * backing file. Attempting to read from the stream after skipping past
254      * the end will result in -1 indicating the end of the file.
255      *
256      * @param      n   the number of bytes to be skipped.
257      * @return     the actual number of bytes skipped.
258      * @exception  IOException  if n is negative, if the stream does not
259      *             support seek, or if an I/O error occurs.
260      */
261     public native long skip(long n) throws IOException;
262 
263     /**
264      * Returns an estimate of the number of remaining bytes that can be read (or
265      * skipped over) from this input stream without blocking by the next
266      * invocation of a method for this input stream. Returns 0 when the file
267      * position is beyond EOF. The next invocation might be the same thread
268      * or another thread. A single read or skip of this many bytes will not
269      * block, but may read or skip fewer bytes.
270      *
271      * <p> In some cases, a non-blocking read (or skip) may appear to be
272      * blocked when it is merely slow, for example when reading large
273      * files over slow networks.
274      *
275      * @return     an estimate of the number of remaining bytes that can be read
276      *             (or skipped over) from this input stream without blocking.
277      * @exception  IOException  if this file input stream has been closed by calling
278      *             {@code close} or an I/O error occurs.
279      */
280     public native int available() throws IOException;
281 
282     /**
283      * Closes this file input stream and releases any system resources
284      * associated with the stream.
285      *
286      * <p> If this stream has an associated channel then the channel is closed
287      * as well.
288      *
289      * @exception  IOException  if an I/O error occurs.
290      *
291      * @revised 1.4
292      * @spec JSR-51
293      */
294     public void close() throws IOException {
295         synchronized (closeLock) {
296             if (closed) {
297                 return;
298             }
299             closed = true;
300         }
301         if (channel != null) {
302            channel.close();
303         }
304 
305         fd.closeAll(new Closeable() {
306             public void close() throws IOException {
307                close0();
308            }
309         });
310     }
311 
312     /**
313      * Returns the <code>FileDescriptor</code>
314      * object  that represents the connection to
315      * the actual file in the file system being
316      * used by this <code>FileInputStream</code>.
317      *
318      * @return     the file descriptor object associated with this stream.
319      * @exception  IOException  if an I/O error occurs.
320      * @see        java.io.FileDescriptor
321      */
322     public final FileDescriptor getFD() throws IOException {
323         if (fd != null) {
324             return fd;
325         }
326         throw new IOException();
327     }
328 
329     /**
330      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
331      * object associated with this file input stream.
332      *
333      * <p> The initial {@link java.nio.channels.FileChannel#position()
334      * position} of the returned channel will be equal to the
335      * number of bytes read from the file so far.  Reading bytes from this
336      * stream will increment the channel's position.  Changing the channel's
337      * position, either explicitly or by reading, will change this stream's
338      * file position.
339      *
340      * @return  the file channel associated with this file input stream
341      *
342      * @since 1.4
343      * @spec JSR-51
344      */
345     public FileChannel getChannel() {
346         synchronized (this) {
347             if (channel == null) {
348                 channel = FileChannelImpl.open(fd, true, false, this);
349             }
350             return channel;
351         }
352     }
353 
354     private static native void initIDs();
355 
356     private native void close0() throws IOException;
357 
358     static {
359         initIDs();
360     }
361 
362     /**
363      * Ensures that the <code>close</code> method of this file input stream is
364      * called when there are no more references to it.
365      *
366      * @exception  IOException  if an I/O error occurs.
367      * @see        java.io.FileInputStream#close()
368      */
369     protected void finalize() throws IOException {
370         if ((fd != null) &&  (fd != FileDescriptor.in)) {
371             /* if fd is shared, the references in FileDescriptor
372              * will ensure that finalizer is only called when
373              * safe to do so. All references using the fd have
374              * become unreachable. We can call close()
375              */
376             close();
377         }
378     }
379 }