< prev index next >

src/java.base/share/classes/java/io/FileInputStream.java

Print this page

 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  *

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 

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.

 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.misc.Blocker;
 31 import jdk.internal.util.ArraysSupport;
 32 import sun.nio.ch.FileChannelImpl;
 33 
 34 /**
 35  * A {@code FileInputStream} obtains input bytes
 36  * from a file in a file system. What files
 37  * are  available depends on the host environment.
 38  *
 39  * <p>{@code FileInputStream} is meant for reading streams of raw bytes
 40  * such as image data. For reading streams of characters, consider using
 41  * {@code FileReader}.
 42  *
 43  * @apiNote
 44  * To release resources used by this stream {@link #close} should be called
 45  * directly or by try-with-resources. Subclasses are responsible for the cleanup
 46  * of resources acquired by the subclass.
 47  * Subclasses that override {@link #finalize} in order to perform cleanup
 48  * should be modified to use alternative cleanup mechanisms such as
 49  * {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
 50  *

197 
198         /*
199          * FileDescriptor is being shared by streams.
200          * Register this stream with FileDescriptor tracker.
201          */
202         fd.attach(this);
203     }
204 
205     /**
206      * Opens the specified file for reading.
207      * @param name the name of the file
208      */
209     private native void open0(String name) throws FileNotFoundException;
210 
211     // wrap native call to allow instrumentation
212     /**
213      * Opens the specified file for reading.
214      * @param name the name of the file
215      */
216     private void open(String name) throws FileNotFoundException {
217         if (Thread.currentThread().isVirtual()) {
218             Blocker.managedBlock(() -> open0(name));
219         } else {
220             open0(name);
221         }
222     }
223 
224     /**
225      * Reads a byte of data from this input stream. This method blocks
226      * if no input is yet available.
227      *
228      * @return     the next byte of data, or {@code -1} if the end of the
229      *             file is reached.
230      * @throws     IOException  if an I/O error occurs.
231      */
232     public int read() throws IOException {
233         if (Thread.currentThread().isVirtual()) {
234             return Blocker.managedBlock(() -> read0());
235         } else {
236             return read0();
237         }
238     }
239 
240     private native int read0() throws IOException;
241 
242     /**
243      * Reads a subarray as a sequence of bytes.
244      * @param     b the data to be written
245      * @param     off the start offset in the data
246      * @param     len the number of bytes that are written
247      * @throws    IOException If an I/O error has occurred.
248      */
249     private native int readBytes(byte[] b, int off, int len) throws IOException;
250 
251     /**
252      * Reads up to {@code b.length} bytes of data from this input
253      * stream into an array of bytes. This method blocks until some input
254      * is available.
255      *
256      * @param      b   the buffer into which the data is read.
257      * @return     the total number of bytes read into the buffer, or
258      *             {@code -1} if there is no more data because the end of
259      *             the file has been reached.
260      * @throws     IOException  if an I/O error occurs.
261      */
262     public int read(byte[] b) throws IOException {
263         if (Thread.currentThread().isVirtual()) {
264             return Blocker.managedBlock(() -> readBytes(b, 0, b.length));
265         } else {
266             return readBytes(b, 0, b.length);
267         }
268     }
269 
270     /**
271      * Reads up to {@code len} bytes of data from this input stream
272      * into an array of bytes. If {@code len} is not zero, the method
273      * blocks until some input is available; otherwise, no
274      * bytes are read and {@code 0} is returned.
275      *
276      * @param      b     the buffer into which the data is read.
277      * @param      off   the start offset in the destination array {@code b}
278      * @param      len   the maximum number of bytes read.
279      * @return     the total number of bytes read into the buffer, or
280      *             {@code -1} if there is no more data because the end of
281      *             the file has been reached.
282      * @throws     NullPointerException If {@code b} is {@code null}.
283      * @throws     IndexOutOfBoundsException If {@code off} is negative,
284      *             {@code len} is negative, or {@code len} is greater than
285      *             {@code b.length - off}
286      * @throws     IOException  if an I/O error occurs.
287      */
288     public int read(byte[] b, int off, int len) throws IOException {
289         if (Thread.currentThread().isVirtual()) {
290             return Blocker.managedBlock(() -> readBytes(b, off, len));
291         } else {
292             return readBytes(b, off, len);
293         }
294     }
295 
296     public byte[] readAllBytes() throws IOException {
297         long length = length();
298         long position = position();
299         long size = length - position;
300 
301         if (length <= 0 || size <= 0)
302             return super.readAllBytes();
303 
304         if (size > (long) Integer.MAX_VALUE) {
305             String msg =
306                 String.format("Required array size too large for %s: %d = %d - %d",
307                     path, size, length, position);
308             throw new OutOfMemoryError(msg);
309         }
310 
311         int capacity = (int)size;
312         byte[] buf = new byte[capacity];
313 

373 
374     /**
375      * {@inheritDoc}
376      */
377     public long transferTo(OutputStream out) throws IOException {
378         long transferred = 0L;
379         if (out instanceof FileOutputStream fos) {
380             FileChannel fc = getChannel();
381             long pos = fc.position();
382             transferred = fc.transferTo(pos, Long.MAX_VALUE, fos.getChannel());
383             long newPos = pos + transferred;
384             fc.position(newPos);
385             if (newPos >= fc.size()) {
386                 return transferred;
387             }
388         }
389         return transferred + super.transferTo(out);
390     }
391 
392     private long length() throws IOException {
393         if (Thread.currentThread().isVirtual()) {
394             return Blocker.managedBlock(() -> length0());
395         } else {
396             return length0();
397         }
398     }
399     private native long length0() throws IOException;
400 
401     private long position() throws IOException {
402         if (Thread.currentThread().isVirtual()) {
403             return Blocker.managedBlock(() -> position0());
404         } else {
405             return position0();
406         }
407     }
408     private native long position0() throws IOException;
409 
410     /**
411      * Skips over and discards {@code n} bytes of data from the
412      * input stream.
413      *
414      * <p>The {@code skip} method may, for a variety of
415      * reasons, end up skipping over some smaller number of bytes,
416      * possibly {@code 0}. If {@code n} is negative, the method
417      * will try to skip backwards. In case the backing file does not support
418      * backward skip at its current position, an {@code IOException} is
419      * thrown. The actual number of bytes skipped is returned. If it skips
420      * forwards, it returns a positive value. If it skips backwards, it
421      * returns a negative value.
422      *
423      * <p>This method may skip more bytes than what are remaining in the
424      * backing file. This produces no exception and the number of bytes skipped
425      * may include some number of bytes that were beyond the EOF of the
426      * backing file. Attempting to read from the stream after skipping past
427      * the end will result in -1 indicating the end of the file.
428      *
429      * @param      n   the number of bytes to be skipped.
430      * @return     the actual number of bytes skipped.
431      * @throws     IOException  if n is negative, if the stream does not
432      *             support seek, or if an I/O error occurs.
433      */
434     public long skip(long n) throws IOException {
435         if (Thread.currentThread().isVirtual()) {
436             return Blocker.managedBlock(() -> skip0(n));
437         } else {
438             return skip0(n);
439         }
440     }
441 
442     private native long skip0(long n) throws IOException;
443 
444     /**
445      * Returns an estimate of the number of remaining bytes that can be read (or
446      * skipped over) from this input stream without blocking by the next
447      * invocation of a method for this input stream. Returns 0 when the file
448      * position is beyond EOF. The next invocation might be the same thread
449      * or another thread. A single read or skip of this many bytes will not
450      * block, but may read or skip fewer bytes.
451      *
452      * <p> In some cases, a non-blocking read (or skip) may appear to be
453      * blocked when it is merely slow, for example when reading large
454      * files over slow networks.
455      *
456      * @return     an estimate of the number of remaining bytes that can be read
457      *             (or skipped over) from this input stream without blocking.
458      * @throws     IOException  if this file input stream has been closed by calling
459      *             {@code close} or an I/O error occurs.
460      */
461     public int available() throws IOException {
462         if (Thread.currentThread().isVirtual()) {
463             return Blocker.managedBlock(() -> available0());
464         } else {
465             return available0();
466         }
467     }
468 
469     private native int available0() throws IOException;
470 
471     /**
472      * Closes this file input stream and releases any system resources
473      * associated with the stream.
474      *
475      * <p> If this stream has an associated channel then the channel is closed
476      * as well.
477      *
478      * @apiNote
479      * Overriding {@link #close} to perform cleanup actions is reliable
480      * only when called directly or when called by try-with-resources.
481      * Do not depend on finalization to invoke {@code close};
482      * finalization is not reliable and is deprecated.
483      * If cleanup of native resources is needed, other mechanisms such as
484      * {@linkplain java.lang.ref.Cleaner} should be used.
485      *
486      * @throws     IOException  if an I/O error occurs.
< prev index next >