1 /*
  2  * Copyright (c) 1994, 2021, 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 java.util.Arrays;
 30 import jdk.internal.util.ArraysSupport;
 31 import sun.nio.ch.FileChannelImpl;
 32 
 33 /**
 34  * A {@code FileInputStream} 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} is meant for reading streams of raw bytes
 39  * such as image data. For reading streams of characters, consider using
 40  * {@code FileReader}.
 41  *
 42  * @apiNote
 43  * To release resources used by this stream {@link #close} should be called
 44  * directly or by try-with-resources. Subclasses are responsible for the cleanup
 45  * of resources acquired by the subclass.
 46  * Subclasses that override {@link #finalize} in order to perform cleanup
 47  * should be modified to use alternative cleanup mechanisms such as
 48  * {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
 49  *
 50  * @implSpec
 51  * If this FileInputStream has been subclassed and the {@link #close}
 52  * method has been overridden, the {@link #close} method will be
 53  * called when the FileInputStream is unreachable.
 54  * Otherwise, it is implementation specific how the resource cleanup described in
 55  * {@link #close} is performed.
 56  *
 57  * @author  Arthur van Hoff
 58  * @see     java.io.File
 59  * @see     java.io.FileDescriptor
 60  * @see     java.io.FileOutputStream
 61  * @see     java.nio.file.Files#newInputStream
 62  * @since   1.0
 63  */
 64 public class FileInputStream extends InputStream
 65 {
 66     private static final int DEFAULT_BUFFER_SIZE = 8192;
 67 
 68     /* File Descriptor - handle to the open file */
 69     private final FileDescriptor fd;
 70 
 71     /**
 72      * The path of the referenced file
 73      * (null if the stream is created with a file descriptor)
 74      */
 75     private final String path;
 76 
 77     private volatile FileChannel channel;
 78 
 79     private final Object closeLock = new Object();
 80 
 81     private volatile boolean closed;
 82 
 83     /**
 84      * Creates a {@code FileInputStream} by
 85      * opening a connection to an actual file,
 86      * the file named by the path name {@code name}
 87      * in the file system.  A new {@code FileDescriptor}
 88      * object is created to represent this file
 89      * connection.
 90      * <p>
 91      * First, if there is a security
 92      * manager, its {@code checkRead} method
 93      * is called with the {@code name} argument
 94      * as its argument.
 95      * <p>
 96      * If the named file does not exist, is a directory rather than a regular
 97      * file, or for some other reason cannot be opened for reading then a
 98      * {@code FileNotFoundException} is thrown.
 99      *
100      * @param      name   the system-dependent file name.
101      * @throws     FileNotFoundException  if the file does not exist,
102      *             is a directory rather than a regular file,
103      *             or for some other reason cannot be opened for
104      *             reading.
105      * @throws     SecurityException      if a security manager exists and its
106      *             {@code checkRead} method denies read access
107      *             to the file.
108      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
109      */
110     public FileInputStream(String name) throws FileNotFoundException {
111         this(name != null ? new File(name) : null);
112     }
113 
114     /**
115      * Creates a {@code FileInputStream} by
116      * opening a connection to an actual file,
117      * the file named by the {@code File}
118      * object {@code file} in the file system.
119      * A new {@code FileDescriptor} object
120      * is created to represent this file connection.
121      * <p>
122      * First, if there is a security manager,
123      * its {@code checkRead} method  is called
124      * with the path represented by the {@code file}
125      * argument as its argument.
126      * <p>
127      * If the named file does not exist, is a directory rather than a regular
128      * file, or for some other reason cannot be opened for reading then a
129      * {@code FileNotFoundException} is thrown.
130      *
131      * @param      file   the file to be opened for reading.
132      * @throws     FileNotFoundException  if the file does not exist,
133      *             is a directory rather than a regular file,
134      *             or for some other reason cannot be opened for
135      *             reading.
136      * @throws     SecurityException      if a security manager exists and its
137      *             {@code checkRead} method denies read access to the file.
138      * @see        java.io.File#getPath()
139      * @see        java.lang.SecurityManager#checkRead(java.lang.String)
140      */
141     public FileInputStream(File file) throws FileNotFoundException {
142         String name = (file != null ? file.getPath() : null);
143         @SuppressWarnings("removal")
144         SecurityManager security = System.getSecurityManager();
145         if (security != null) {
146             security.checkRead(name);
147         }
148         if (name == null) {
149             throw new NullPointerException();
150         }
151         if (file.isInvalid()) {
152             throw new FileNotFoundException("Invalid file path");
153         }
154         fd = new FileDescriptor();
155         fd.attach(this);
156         path = name;
157         open(name);
158         FileCleanable.register(fd);       // open set the fd, register the cleanup
159     }
160 
161     /**
162      * Creates a {@code FileInputStream} by using the file descriptor
163      * {@code fdObj}, which represents an existing connection to an
164      * actual file in the file system.
165      * <p>
166      * If there is a security manager, its {@code checkRead} method is
167      * called with the file descriptor {@code fdObj} as its argument to
168      * see if it's ok to read the file descriptor. If read access is denied
169      * to the file descriptor a {@code SecurityException} is thrown.
170      * <p>
171      * If {@code fdObj} is null then a {@code NullPointerException}
172      * is thrown.
173      * <p>
174      * This constructor does not throw an exception if {@code fdObj}
175      * is {@link java.io.FileDescriptor#valid() invalid}.
176      * However, if the methods are invoked on the resulting stream to attempt
177      * I/O on the stream, an {@code IOException} is thrown.
178      *
179      * @param      fdObj   the file descriptor to be opened for reading.
180      * @throws     SecurityException      if a security manager exists and its
181      *             {@code checkRead} method denies read access to the
182      *             file descriptor.
183      * @see        SecurityManager#checkRead(java.io.FileDescriptor)
184      */
185     public FileInputStream(FileDescriptor fdObj) {
186         @SuppressWarnings("removal")
187         SecurityManager security = System.getSecurityManager();
188         if (fdObj == null) {
189             throw new NullPointerException();
190         }
191         if (security != null) {
192             security.checkRead(fdObj);
193         }
194         fd = fdObj;
195         path = null;
196 
197         /*
198          * FileDescriptor is being shared by streams.
199          * Register this stream with FileDescriptor tracker.
200          */
201         fd.attach(this);
202     }
203 
204     /**
205      * Opens the specified file for reading.
206      * @param name the name of the file
207      */
208     private native void open0(String name) throws FileNotFoundException;
209 
210     // wrap native call to allow instrumentation
211     /**
212      * Opens the specified file for reading.
213      * @param name the name of the file
214      */
215     private void open(String name) throws FileNotFoundException {
216         open0(name);
217     }
218 
219     /**
220      * Reads a byte of data from this input stream. This method blocks
221      * if no input is yet available.
222      *
223      * @return     the next byte of data, or {@code -1} if the end of the
224      *             file is reached.
225      * @throws     IOException  if an I/O error occurs.
226      */
227     public int read() throws IOException {
228         return read0();
229     }
230 
231     private native int read0() throws IOException;
232 
233     /**
234      * Reads a subarray as a sequence of bytes.
235      * @param     b the data to be written
236      * @param     off the start offset in the data
237      * @param     len the number of bytes that are written
238      * @throws    IOException If an I/O error has occurred.
239      */
240     private native int readBytes(byte[] b, int off, int len) throws IOException;
241 
242     /**
243      * Reads up to {@code b.length} bytes of data from this input
244      * stream into an array of bytes. This method blocks until some input
245      * is available.
246      *
247      * @param      b   the buffer into which the data is read.
248      * @return     the total number of bytes read into the buffer, or
249      *             {@code -1} if there is no more data because the end of
250      *             the file has been reached.
251      * @throws     IOException  if an I/O error occurs.
252      */
253     public int read(byte[] b) throws IOException {
254         return readBytes(b, 0, b.length);
255     }
256 
257     /**
258      * Reads up to {@code len} bytes of data from this input stream
259      * into an array of bytes. If {@code len} is not zero, the method
260      * blocks until some input is available; otherwise, no
261      * bytes are read and {@code 0} is returned.
262      *
263      * @param      b     the buffer into which the data is read.
264      * @param      off   the start offset in the destination array {@code b}
265      * @param      len   the maximum number of bytes read.
266      * @return     the total number of bytes read into the buffer, or
267      *             {@code -1} if there is no more data because the end of
268      *             the file has been reached.
269      * @throws     NullPointerException If {@code b} is {@code null}.
270      * @throws     IndexOutOfBoundsException If {@code off} is negative,
271      *             {@code len} is negative, or {@code len} is greater than
272      *             {@code b.length - off}
273      * @throws     IOException  if an I/O error occurs.
274      */
275     public int read(byte[] b, int off, int len) throws IOException {
276         return readBytes(b, off, len);
277     }
278 
279     public byte[] readAllBytes() throws IOException {
280         long length = length();
281         long position = position();
282         long size = length - position;
283 
284         if (length <= 0 || size <= 0)
285             return super.readAllBytes();
286 
287         if (size > (long) Integer.MAX_VALUE) {
288             String msg =
289                 String.format("Required array size too large for %s: %d = %d - %d",
290                     path, size, length, position);
291             throw new OutOfMemoryError(msg);
292         }
293 
294         int capacity = (int)size;
295         byte[] buf = new byte[capacity];
296 
297         int nread = 0;
298         int n;
299         for (;;) {
300             // read to EOF which may read more or less than initial size, e.g.,
301             // file is truncated while we are reading
302             while ((n = read(buf, nread, capacity - nread)) > 0)
303                 nread += n;
304 
305             // if last call to read() returned -1, we are done; otherwise,
306             // try to read one more byte and if that fails we're done too
307             if (n < 0 || (n = read()) < 0)
308                 break;
309 
310             // one more byte was read; need to allocate a larger buffer
311             capacity = Math.max(ArraysSupport.newLength(capacity,
312                                                         1,         // min growth
313                                                         capacity), // pref growth
314                                 DEFAULT_BUFFER_SIZE);
315             buf = Arrays.copyOf(buf, capacity);
316             buf[nread++] = (byte)n;
317         }
318         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
319     }
320 
321     public byte[] readNBytes(int len) throws IOException {
322         if (len < 0)
323             throw new IllegalArgumentException("len < 0");
324         if (len == 0)
325             return new byte[0];
326 
327         long length = length();
328         long position = position();
329         long size = length - position;
330 
331         if (length <= 0 || size <= 0)
332             return super.readNBytes(len);
333 
334         int capacity = (int)Math.min(len, size);
335         byte[] buf = new byte[capacity];
336 
337         int remaining = capacity;
338         int nread = 0;
339         int n;
340         do {
341             n = read(buf, nread, remaining);
342             if (n > 0) {
343                 nread += n;
344                 remaining -= n;
345             } else if (n == 0) {
346                 // Block until a byte is read or EOF is detected
347                 byte b = (byte)read();
348                 if (b == -1 )
349                     break;
350                 buf[nread++] = b;
351                 remaining--;
352             }
353         } while (n >= 0 && remaining > 0);
354         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
355     }
356 
357     /**
358      * {@inheritDoc}
359      */
360     public long transferTo(OutputStream out) throws IOException {
361         long transferred = 0L;
362         if (out instanceof FileOutputStream fos) {
363             FileChannel fc = getChannel();
364             long pos = fc.position();
365             transferred = fc.transferTo(pos, Long.MAX_VALUE, fos.getChannel());
366             long newPos = pos + transferred;
367             fc.position(newPos);
368             if (newPos >= fc.size()) {
369                 return transferred;
370             }
371         }
372         return transferred + super.transferTo(out);
373     }
374 
375     private long length() throws IOException {
376         return length0();
377     }
378     private native long length0() throws IOException;
379 
380     private long position() throws IOException {
381         return position0();
382     }
383     private native long position0() throws IOException;
384 
385     /**
386      * Skips over and discards {@code n} bytes of data from the
387      * input stream.
388      *
389      * <p>The {@code skip} method may, for a variety of
390      * reasons, end up skipping over some smaller number of bytes,
391      * possibly {@code 0}. If {@code n} is negative, the method
392      * will try to skip backwards. In case the backing file does not support
393      * backward skip at its current position, an {@code IOException} is
394      * thrown. The actual number of bytes skipped is returned. If it skips
395      * forwards, it returns a positive value. If it skips backwards, it
396      * returns a negative value.
397      *
398      * <p>This method may skip more bytes than what are remaining in the
399      * backing file. This produces no exception and the number of bytes skipped
400      * may include some number of bytes that were beyond the EOF of the
401      * backing file. Attempting to read from the stream after skipping past
402      * the end will result in -1 indicating the end of the file.
403      *
404      * @param      n   the number of bytes to be skipped.
405      * @return     the actual number of bytes skipped.
406      * @throws     IOException  if n is negative, if the stream does not
407      *             support seek, or if an I/O error occurs.
408      */
409     public long skip(long n) throws IOException {
410         return skip0(n);
411     }
412 
413     private native long skip0(long n) throws IOException;
414 
415     /**
416      * Returns an estimate of the number of remaining bytes that can be read (or
417      * skipped over) from this input stream without blocking by the next
418      * invocation of a method for this input stream. Returns 0 when the file
419      * position is beyond EOF. The next invocation might be the same thread
420      * or another thread. A single read or skip of this many bytes will not
421      * block, but may read or skip fewer bytes.
422      *
423      * <p> In some cases, a non-blocking read (or skip) may appear to be
424      * blocked when it is merely slow, for example when reading large
425      * files over slow networks.
426      *
427      * @return     an estimate of the number of remaining bytes that can be read
428      *             (or skipped over) from this input stream without blocking.
429      * @throws     IOException  if this file input stream has been closed by calling
430      *             {@code close} or an I/O error occurs.
431      */
432     public int available() throws IOException {
433         return available0();
434     }
435 
436     private native int available0() throws IOException;
437 
438     /**
439      * Closes this file input stream and releases any system resources
440      * associated with the stream.
441      *
442      * <p> If this stream has an associated channel then the channel is closed
443      * as well.
444      *
445      * @apiNote
446      * Overriding {@link #close} to perform cleanup actions is reliable
447      * only when called directly or when called by try-with-resources.
448      * Do not depend on finalization to invoke {@code close};
449      * finalization is not reliable and is deprecated.
450      * If cleanup of native resources is needed, other mechanisms such as
451      * {@linkplain java.lang.ref.Cleaner} should be used.
452      *
453      * @throws     IOException  if an I/O error occurs.
454      *
455      * @revised 1.4
456      */
457     public void close() throws IOException {
458         if (closed) {
459             return;
460         }
461         synchronized (closeLock) {
462             if (closed) {
463                 return;
464             }
465             closed = true;
466         }
467 
468         FileChannel fc = channel;
469         if (fc != null) {
470             // possible race with getChannel(), benign since
471             // FileChannel.close is final and idempotent
472             fc.close();
473         }
474 
475         fd.closeAll(new Closeable() {
476             public void close() throws IOException {
477                fd.close();
478            }
479         });
480     }
481 
482     /**
483      * Returns the {@code FileDescriptor}
484      * object  that represents the connection to
485      * the actual file in the file system being
486      * used by this {@code FileInputStream}.
487      *
488      * @return     the file descriptor object associated with this stream.
489      * @throws     IOException  if an I/O error occurs.
490      * @see        java.io.FileDescriptor
491      */
492     public final FileDescriptor getFD() throws IOException {
493         if (fd != null) {
494             return fd;
495         }
496         throw new IOException();
497     }
498 
499     /**
500      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}
501      * object associated with this file input stream.
502      *
503      * <p> The initial {@link java.nio.channels.FileChannel#position()
504      * position} of the returned channel will be equal to the
505      * number of bytes read from the file so far.  Reading bytes from this
506      * stream will increment the channel's position.  Changing the channel's
507      * position, either explicitly or by reading, will change this stream's
508      * file position.
509      *
510      * @return  the file channel associated with this file input stream
511      *
512      * @since 1.4
513      */
514     public FileChannel getChannel() {
515         FileChannel fc = this.channel;
516         if (fc == null) {
517             synchronized (this) {
518                 fc = this.channel;
519                 if (fc == null) {
520                     this.channel = fc = FileChannelImpl.open(fd, path, true,
521                         false, false, this);
522                     if (closed) {
523                         try {
524                             // possible race with close(), benign since
525                             // FileChannel.close is final and idempotent
526                             fc.close();
527                         } catch (IOException ioe) {
528                             throw new InternalError(ioe); // should not happen
529                         }
530                     }
531                 }
532             }
533         }
534         return fc;
535     }
536 
537     private static native void initIDs();
538 
539     static {
540         initIDs();
541     }
542 }