Path: blob/master/src/java.base/share/classes/java/io/FileInputStream.java
41152 views
/*1* Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.io;2627import java.nio.channels.FileChannel;28import java.util.Arrays;29import jdk.internal.util.ArraysSupport;30import sun.nio.ch.FileChannelImpl;3132/**33* A {@code FileInputStream} obtains input bytes34* from a file in a file system. What files35* are available depends on the host environment.36*37* <p>{@code FileInputStream} is meant for reading streams of raw bytes38* such as image data. For reading streams of characters, consider using39* {@code FileReader}.40*41* @apiNote42* To release resources used by this stream {@link #close} should be called43* directly or by try-with-resources. Subclasses are responsible for the cleanup44* of resources acquired by the subclass.45* Subclasses that override {@link #finalize} in order to perform cleanup46* should be modified to use alternative cleanup mechanisms such as47* {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.48*49* @implSpec50* If this FileInputStream has been subclassed and the {@link #close}51* method has been overridden, the {@link #close} method will be52* called when the FileInputStream is unreachable.53* Otherwise, it is implementation specific how the resource cleanup described in54* {@link #close} is performed.55*56* @author Arthur van Hoff57* @see java.io.File58* @see java.io.FileDescriptor59* @see java.io.FileOutputStream60* @see java.nio.file.Files#newInputStream61* @since 1.062*/63public class FileInputStream extends InputStream64{65private static final int DEFAULT_BUFFER_SIZE = 8192;6667/* File Descriptor - handle to the open file */68private final FileDescriptor fd;6970/**71* The path of the referenced file72* (null if the stream is created with a file descriptor)73*/74private final String path;7576private volatile FileChannel channel;7778private final Object closeLock = new Object();7980private volatile boolean closed;8182/**83* Creates a {@code FileInputStream} by84* opening a connection to an actual file,85* the file named by the path name {@code name}86* in the file system. A new {@code FileDescriptor}87* object is created to represent this file88* connection.89* <p>90* First, if there is a security91* manager, its {@code checkRead} method92* is called with the {@code name} argument93* as its argument.94* <p>95* If the named file does not exist, is a directory rather than a regular96* file, or for some other reason cannot be opened for reading then a97* {@code FileNotFoundException} is thrown.98*99* @param name the system-dependent file name.100* @throws FileNotFoundException if the file does not exist,101* is a directory rather than a regular file,102* or for some other reason cannot be opened for103* reading.104* @throws SecurityException if a security manager exists and its105* {@code checkRead} method denies read access106* to the file.107* @see java.lang.SecurityManager#checkRead(java.lang.String)108*/109public FileInputStream(String name) throws FileNotFoundException {110this(name != null ? new File(name) : null);111}112113/**114* Creates a {@code FileInputStream} by115* opening a connection to an actual file,116* the file named by the {@code File}117* object {@code file} in the file system.118* A new {@code FileDescriptor} object119* is created to represent this file connection.120* <p>121* First, if there is a security manager,122* its {@code checkRead} method is called123* with the path represented by the {@code file}124* argument as its argument.125* <p>126* If the named file does not exist, is a directory rather than a regular127* file, or for some other reason cannot be opened for reading then a128* {@code FileNotFoundException} is thrown.129*130* @param file the file to be opened for reading.131* @throws FileNotFoundException if the file does not exist,132* is a directory rather than a regular file,133* or for some other reason cannot be opened for134* reading.135* @throws SecurityException if a security manager exists and its136* {@code checkRead} method denies read access to the file.137* @see java.io.File#getPath()138* @see java.lang.SecurityManager#checkRead(java.lang.String)139*/140public FileInputStream(File file) throws FileNotFoundException {141String name = (file != null ? file.getPath() : null);142@SuppressWarnings("removal")143SecurityManager security = System.getSecurityManager();144if (security != null) {145security.checkRead(name);146}147if (name == null) {148throw new NullPointerException();149}150if (file.isInvalid()) {151throw new FileNotFoundException("Invalid file path");152}153fd = new FileDescriptor();154fd.attach(this);155path = name;156open(name);157FileCleanable.register(fd); // open set the fd, register the cleanup158}159160/**161* Creates a {@code FileInputStream} by using the file descriptor162* {@code fdObj}, which represents an existing connection to an163* actual file in the file system.164* <p>165* If there is a security manager, its {@code checkRead} method is166* called with the file descriptor {@code fdObj} as its argument to167* see if it's ok to read the file descriptor. If read access is denied168* to the file descriptor a {@code SecurityException} is thrown.169* <p>170* If {@code fdObj} is null then a {@code NullPointerException}171* is thrown.172* <p>173* This constructor does not throw an exception if {@code fdObj}174* is {@link java.io.FileDescriptor#valid() invalid}.175* However, if the methods are invoked on the resulting stream to attempt176* I/O on the stream, an {@code IOException} is thrown.177*178* @param fdObj the file descriptor to be opened for reading.179* @throws SecurityException if a security manager exists and its180* {@code checkRead} method denies read access to the181* file descriptor.182* @see SecurityManager#checkRead(java.io.FileDescriptor)183*/184public FileInputStream(FileDescriptor fdObj) {185@SuppressWarnings("removal")186SecurityManager security = System.getSecurityManager();187if (fdObj == null) {188throw new NullPointerException();189}190if (security != null) {191security.checkRead(fdObj);192}193fd = fdObj;194path = null;195196/*197* FileDescriptor is being shared by streams.198* Register this stream with FileDescriptor tracker.199*/200fd.attach(this);201}202203/**204* Opens the specified file for reading.205* @param name the name of the file206*/207private native void open0(String name) throws FileNotFoundException;208209// wrap native call to allow instrumentation210/**211* Opens the specified file for reading.212* @param name the name of the file213*/214private void open(String name) throws FileNotFoundException {215open0(name);216}217218/**219* Reads a byte of data from this input stream. This method blocks220* if no input is yet available.221*222* @return the next byte of data, or {@code -1} if the end of the223* file is reached.224* @throws IOException if an I/O error occurs.225*/226public int read() throws IOException {227return read0();228}229230private native int read0() throws IOException;231232/**233* Reads a subarray as a sequence of bytes.234* @param b the data to be written235* @param off the start offset in the data236* @param len the number of bytes that are written237* @throws IOException If an I/O error has occurred.238*/239private native int readBytes(byte b[], int off, int len) throws IOException;240241/**242* Reads up to {@code b.length} bytes of data from this input243* stream into an array of bytes. This method blocks until some input244* is available.245*246* @param b the buffer into which the data is read.247* @return the total number of bytes read into the buffer, or248* {@code -1} if there is no more data because the end of249* the file has been reached.250* @throws IOException if an I/O error occurs.251*/252public int read(byte b[]) throws IOException {253return readBytes(b, 0, b.length);254}255256/**257* Reads up to {@code len} bytes of data from this input stream258* into an array of bytes. If {@code len} is not zero, the method259* blocks until some input is available; otherwise, no260* bytes are read and {@code 0} is returned.261*262* @param b the buffer into which the data is read.263* @param off the start offset in the destination array {@code b}264* @param len the maximum number of bytes read.265* @return the total number of bytes read into the buffer, or266* {@code -1} if there is no more data because the end of267* the file has been reached.268* @throws NullPointerException If {@code b} is {@code null}.269* @throws IndexOutOfBoundsException If {@code off} is negative,270* {@code len} is negative, or {@code len} is greater than271* {@code b.length - off}272* @throws IOException if an I/O error occurs.273*/274public int read(byte b[], int off, int len) throws IOException {275return readBytes(b, off, len);276}277278public byte[] readAllBytes() throws IOException {279long length = length();280long position = position();281long size = length - position;282283if (length <= 0 || size <= 0)284return super.readAllBytes();285286if (size > (long) Integer.MAX_VALUE) {287String msg =288String.format("Required array size too large for %s: %d = %d - %d",289path, size, length, position);290throw new OutOfMemoryError(msg);291}292293int capacity = (int)size;294byte[] buf = new byte[capacity];295296int nread = 0;297int n;298for (;;) {299// read to EOF which may read more or less than initial size, e.g.,300// file is truncated while we are reading301while ((n = read(buf, nread, capacity - nread)) > 0)302nread += n;303304// if last call to read() returned -1, we are done; otherwise,305// try to read one more byte and if that fails we're done too306if (n < 0 || (n = read()) < 0)307break;308309// one more byte was read; need to allocate a larger buffer310capacity = Math.max(ArraysSupport.newLength(capacity,3111, // min growth312capacity), // pref growth313DEFAULT_BUFFER_SIZE);314buf = Arrays.copyOf(buf, capacity);315buf[nread++] = (byte)n;316}317return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);318}319320public byte[] readNBytes(int len) throws IOException {321if (len < 0)322throw new IllegalArgumentException("len < 0");323if (len == 0)324return new byte[0];325326long length = length();327long position = position();328long size = length - position;329330if (length <= 0 || size <= 0)331return super.readNBytes(len);332333int capacity = (int)Math.min(len, size);334byte[] buf = new byte[capacity];335336int remaining = capacity;337int nread = 0;338int n;339do {340n = read(buf, nread, remaining);341if (n > 0 ) {342nread += n;343remaining -= n;344} else if (n == 0) {345// Block until a byte is read or EOF is detected346byte b = (byte)read();347if (b == -1 )348break;349buf[nread++] = b;350remaining--;351}352} while (n >= 0 && remaining > 0);353return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);354}355356private long length() throws IOException {357return length0();358}359private native long length0() throws IOException;360361private long position() throws IOException {362return position0();363}364private native long position0() throws IOException;365366/**367* Skips over and discards {@code n} bytes of data from the368* input stream.369*370* <p>The {@code skip} method may, for a variety of371* reasons, end up skipping over some smaller number of bytes,372* possibly {@code 0}. If {@code n} is negative, the method373* will try to skip backwards. In case the backing file does not support374* backward skip at its current position, an {@code IOException} is375* thrown. The actual number of bytes skipped is returned. If it skips376* forwards, it returns a positive value. If it skips backwards, it377* returns a negative value.378*379* <p>This method may skip more bytes than what are remaining in the380* backing file. This produces no exception and the number of bytes skipped381* may include some number of bytes that were beyond the EOF of the382* backing file. Attempting to read from the stream after skipping past383* the end will result in -1 indicating the end of the file.384*385* @param n the number of bytes to be skipped.386* @return the actual number of bytes skipped.387* @throws IOException if n is negative, if the stream does not388* support seek, or if an I/O error occurs.389*/390public long skip(long n) throws IOException {391return skip0(n);392}393394private native long skip0(long n) throws IOException;395396/**397* Returns an estimate of the number of remaining bytes that can be read (or398* skipped over) from this input stream without blocking by the next399* invocation of a method for this input stream. Returns 0 when the file400* position is beyond EOF. The next invocation might be the same thread401* or another thread. A single read or skip of this many bytes will not402* block, but may read or skip fewer bytes.403*404* <p> In some cases, a non-blocking read (or skip) may appear to be405* blocked when it is merely slow, for example when reading large406* files over slow networks.407*408* @return an estimate of the number of remaining bytes that can be read409* (or skipped over) from this input stream without blocking.410* @throws IOException if this file input stream has been closed by calling411* {@code close} or an I/O error occurs.412*/413public int available() throws IOException {414return available0();415}416417private native int available0() throws IOException;418419/**420* Closes this file input stream and releases any system resources421* associated with the stream.422*423* <p> If this stream has an associated channel then the channel is closed424* as well.425*426* @apiNote427* Overriding {@link #close} to perform cleanup actions is reliable428* only when called directly or when called by try-with-resources.429* Do not depend on finalization to invoke {@code close};430* finalization is not reliable and is deprecated.431* If cleanup of native resources is needed, other mechanisms such as432* {@linkplain java.lang.ref.Cleaner} should be used.433*434* @throws IOException if an I/O error occurs.435*436* @revised 1.4437*/438public void close() throws IOException {439if (closed) {440return;441}442synchronized (closeLock) {443if (closed) {444return;445}446closed = true;447}448449FileChannel fc = channel;450if (fc != null) {451// possible race with getChannel(), benign since452// FileChannel.close is final and idempotent453fc.close();454}455456fd.closeAll(new Closeable() {457public void close() throws IOException {458fd.close();459}460});461}462463/**464* Returns the {@code FileDescriptor}465* object that represents the connection to466* the actual file in the file system being467* used by this {@code FileInputStream}.468*469* @return the file descriptor object associated with this stream.470* @throws IOException if an I/O error occurs.471* @see java.io.FileDescriptor472*/473public final FileDescriptor getFD() throws IOException {474if (fd != null) {475return fd;476}477throw new IOException();478}479480/**481* Returns the unique {@link java.nio.channels.FileChannel FileChannel}482* object associated with this file input stream.483*484* <p> The initial {@link java.nio.channels.FileChannel#position()485* position} of the returned channel will be equal to the486* number of bytes read from the file so far. Reading bytes from this487* stream will increment the channel's position. Changing the channel's488* position, either explicitly or by reading, will change this stream's489* file position.490*491* @return the file channel associated with this file input stream492*493* @since 1.4494*/495public FileChannel getChannel() {496FileChannel fc = this.channel;497if (fc == null) {498synchronized (this) {499fc = this.channel;500if (fc == null) {501this.channel = fc = FileChannelImpl.open(fd, path, true,502false, false, this);503if (closed) {504try {505// possible race with close(), benign since506// FileChannel.close is final and idempotent507fc.close();508} catch (IOException ioe) {509throw new InternalError(ioe); // should not happen510}511}512}513}514}515return fc;516}517518private static native void initIDs();519520static {521initIDs();522}523}524525526