Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/io/FileInputStream.java
38829 views
/*1* Copyright (c) 1994, 2013, 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 sun.nio.ch.FileChannelImpl;293031/**32* A <code>FileInputStream</code> obtains input bytes33* from a file in a file system. What files34* are available depends on the host environment.35*36* <p><code>FileInputStream</code> is meant for reading streams of raw bytes37* such as image data. For reading streams of characters, consider using38* <code>FileReader</code>.39*40* @author Arthur van Hoff41* @see java.io.File42* @see java.io.FileDescriptor43* @see java.io.FileOutputStream44* @see java.nio.file.Files#newInputStream45* @since JDK1.046*/47public48class FileInputStream extends InputStream49{50/* File Descriptor - handle to the open file */51private final FileDescriptor fd;5253/**54* The path of the referenced file55* (null if the stream is created with a file descriptor)56*/57private final String path;5859private FileChannel channel = null;6061private final Object closeLock = new Object();62private volatile boolean closed = false;6364/**65* Creates a <code>FileInputStream</code> by66* opening a connection to an actual file,67* the file named by the path name <code>name</code>68* in the file system. A new <code>FileDescriptor</code>69* object is created to represent this file70* connection.71* <p>72* First, if there is a security73* manager, its <code>checkRead</code> method74* is called with the <code>name</code> argument75* as its argument.76* <p>77* If the named file does not exist, is a directory rather than a regular78* file, or for some other reason cannot be opened for reading then a79* <code>FileNotFoundException</code> is thrown.80*81* @param name the system-dependent file name.82* @exception FileNotFoundException if the file does not exist,83* is a directory rather than a regular file,84* or for some other reason cannot be opened for85* reading.86* @exception SecurityException if a security manager exists and its87* <code>checkRead</code> method denies read access88* to the file.89* @see java.lang.SecurityManager#checkRead(java.lang.String)90*/91public FileInputStream(String name) throws FileNotFoundException {92this(name != null ? new File(name) : null);93}9495/**96* Creates a <code>FileInputStream</code> by97* opening a connection to an actual file,98* the file named by the <code>File</code>99* object <code>file</code> in the file system.100* A new <code>FileDescriptor</code> object101* is created to represent this file connection.102* <p>103* First, if there is a security manager,104* its <code>checkRead</code> method is called105* with the path represented by the <code>file</code>106* argument as its argument.107* <p>108* If the named file does not exist, is a directory rather than a regular109* file, or for some other reason cannot be opened for reading then a110* <code>FileNotFoundException</code> is thrown.111*112* @param file the file to be opened for reading.113* @exception FileNotFoundException if the file does not exist,114* is a directory rather than a regular file,115* or for some other reason cannot be opened for116* reading.117* @exception SecurityException if a security manager exists and its118* <code>checkRead</code> method denies read access to the file.119* @see java.io.File#getPath()120* @see java.lang.SecurityManager#checkRead(java.lang.String)121*/122public FileInputStream(File file) throws FileNotFoundException {123String name = (file != null ? file.getPath() : null);124SecurityManager security = System.getSecurityManager();125if (security != null) {126security.checkRead(name);127}128if (name == null) {129throw new NullPointerException();130}131if (file.isInvalid()) {132throw new FileNotFoundException("Invalid file path");133}134fd = new FileDescriptor();135fd.attach(this);136path = name;137open(name);138}139140/**141* Creates a <code>FileInputStream</code> by using the file descriptor142* <code>fdObj</code>, which represents an existing connection to an143* actual file in the file system.144* <p>145* If there is a security manager, its <code>checkRead</code> method is146* called with the file descriptor <code>fdObj</code> as its argument to147* see if it's ok to read the file descriptor. If read access is denied148* to the file descriptor a <code>SecurityException</code> is thrown.149* <p>150* If <code>fdObj</code> is null then a <code>NullPointerException</code>151* is thrown.152* <p>153* This constructor does not throw an exception if <code>fdObj</code>154* is {@link java.io.FileDescriptor#valid() invalid}.155* However, if the methods are invoked on the resulting stream to attempt156* I/O on the stream, an <code>IOException</code> is thrown.157*158* @param fdObj the file descriptor to be opened for reading.159* @throws SecurityException if a security manager exists and its160* <code>checkRead</code> method denies read access to the161* file descriptor.162* @see SecurityManager#checkRead(java.io.FileDescriptor)163*/164public FileInputStream(FileDescriptor fdObj) {165SecurityManager security = System.getSecurityManager();166if (fdObj == null) {167throw new NullPointerException();168}169if (security != null) {170security.checkRead(fdObj);171}172fd = fdObj;173path = null;174175/*176* FileDescriptor is being shared by streams.177* Register this stream with FileDescriptor tracker.178*/179fd.attach(this);180}181182/**183* Opens the specified file for reading.184* @param name the name of the file185*/186private native void open0(String name) throws FileNotFoundException;187188// wrap native call to allow instrumentation189/**190* Opens the specified file for reading.191* @param name the name of the file192*/193private void open(String name) throws FileNotFoundException {194open0(name);195}196197/**198* Reads a byte of data from this input stream. This method blocks199* if no input is yet available.200*201* @return the next byte of data, or <code>-1</code> if the end of the202* file is reached.203* @exception IOException if an I/O error occurs.204*/205public int read() throws IOException {206return read0();207}208209private native int read0() throws IOException;210211/**212* Reads a subarray as a sequence of bytes.213* @param b the data to be written214* @param off the start offset in the data215* @param len the number of bytes that are written216* @exception IOException If an I/O error has occurred.217*/218private native int readBytes(byte b[], int off, int len) throws IOException;219220/**221* Reads up to <code>b.length</code> bytes of data from this input222* stream into an array of bytes. This method blocks until some input223* is available.224*225* @param b the buffer into which the data is read.226* @return the total number of bytes read into the buffer, or227* <code>-1</code> if there is no more data because the end of228* the file has been reached.229* @exception IOException if an I/O error occurs.230*/231public int read(byte b[]) throws IOException {232return readBytes(b, 0, b.length);233}234235/**236* Reads up to <code>len</code> bytes of data from this input stream237* into an array of bytes. If <code>len</code> is not zero, the method238* blocks until some input is available; otherwise, no239* bytes are read and <code>0</code> is returned.240*241* @param b the buffer into which the data is read.242* @param off the start offset in the destination array <code>b</code>243* @param len the maximum number of bytes read.244* @return the total number of bytes read into the buffer, or245* <code>-1</code> if there is no more data because the end of246* the file has been reached.247* @exception NullPointerException If <code>b</code> is <code>null</code>.248* @exception IndexOutOfBoundsException If <code>off</code> is negative,249* <code>len</code> is negative, or <code>len</code> is greater than250* <code>b.length - off</code>251* @exception IOException if an I/O error occurs.252*/253public int read(byte b[], int off, int len) throws IOException {254return readBytes(b, off, len);255}256257/**258* Skips over and discards <code>n</code> bytes of data from the259* input stream.260*261* <p>The <code>skip</code> method may, for a variety of262* reasons, end up skipping over some smaller number of bytes,263* possibly <code>0</code>. If <code>n</code> is negative, the method264* will try to skip backwards. In case the backing file does not support265* backward skip at its current position, an <code>IOException</code> is266* thrown. The actual number of bytes skipped is returned. If it skips267* forwards, it returns a positive value. If it skips backwards, it268* returns a negative value.269*270* <p>This method may skip more bytes than what are remaining in the271* backing file. This produces no exception and the number of bytes skipped272* may include some number of bytes that were beyond the EOF of the273* backing file. Attempting to read from the stream after skipping past274* the end will result in -1 indicating the end of the file.275*276* @param n the number of bytes to be skipped.277* @return the actual number of bytes skipped.278* @exception IOException if n is negative, if the stream does not279* support seek, or if an I/O error occurs.280*/281public long skip(long n) throws IOException {282return skip0(n);283}284285private native long skip0(long n) throws IOException;286287/**288* Returns an estimate of the number of remaining bytes that can be read (or289* skipped over) from this input stream without blocking by the next290* invocation of a method for this input stream. Returns 0 when the file291* position is beyond EOF. The next invocation might be the same thread292* or another thread. A single read or skip of this many bytes will not293* block, but may read or skip fewer bytes.294*295* <p> In some cases, a non-blocking read (or skip) may appear to be296* blocked when it is merely slow, for example when reading large297* files over slow networks.298*299* @return an estimate of the number of remaining bytes that can be read300* (or skipped over) from this input stream without blocking.301* @exception IOException if this file input stream has been closed by calling302* {@code close} or an I/O error occurs.303*/304public int available() throws IOException {305return available0();306}307308private native int available0() throws IOException;309310/**311* Closes this file input stream and releases any system resources312* associated with the stream.313*314* <p> If this stream has an associated channel then the channel is closed315* as well.316*317* @exception IOException if an I/O error occurs.318*319* @revised 1.4320* @spec JSR-51321*/322public void close() throws IOException {323synchronized (closeLock) {324if (closed) {325return;326}327closed = true;328}329if (channel != null) {330channel.close();331}332333fd.closeAll(new Closeable() {334public void close() throws IOException {335close0();336}337});338}339340/**341* Returns the <code>FileDescriptor</code>342* object that represents the connection to343* the actual file in the file system being344* used by this <code>FileInputStream</code>.345*346* @return the file descriptor object associated with this stream.347* @exception IOException if an I/O error occurs.348* @see java.io.FileDescriptor349*/350public final FileDescriptor getFD() throws IOException {351if (fd != null) {352return fd;353}354throw new IOException();355}356357/**358* Returns the unique {@link java.nio.channels.FileChannel FileChannel}359* object associated with this file input stream.360*361* <p> The initial {@link java.nio.channels.FileChannel#position()362* position} of the returned channel will be equal to the363* number of bytes read from the file so far. Reading bytes from this364* stream will increment the channel's position. Changing the channel's365* position, either explicitly or by reading, will change this stream's366* file position.367*368* @return the file channel associated with this file input stream369*370* @since 1.4371* @spec JSR-51372*/373public FileChannel getChannel() {374synchronized (this) {375if (channel == null) {376channel = FileChannelImpl.open(fd, path, true, false, this);377}378return channel;379}380}381382private static native void initIDs();383384private native void close0() throws IOException;385386static {387initIDs();388}389390/**391* Ensures that the <code>close</code> method of this file input stream is392* called when there are no more references to it.393*394* @exception IOException if an I/O error occurs.395* @see java.io.FileInputStream#close()396*/397protected void finalize() throws IOException {398if ((fd != null) && (fd != FileDescriptor.in)) {399/* if fd is shared, the references in FileDescriptor400* will ensure that finalizer is only called when401* safe to do so. All references using the fd have402* become unreachable. We can call close()403*/404close();405}406}407}408409410