Home » Java » Java InputStream Class Methods

Java InputStream Class Methods

In this article, you will learn about Java InputStream class methods and their usage.

Most of the InputStream methods interact with system resources and have the potential for encountering platform-specific system problems and throwing an IOException.

The constructor for Java InputStream Class is:

InputStream() Constructs an instance of the class.

The following are the methods of InputStream.

int read() throws IOException Read one byte from the data source. Returns the byte in the low-order 8 bits of the return value. If no more data is available, returns -1. If data is not available at the moment of the call, the calling thread is blocked.

int read(byte dest[]) throws IOException Reads bytes from the data source into the dest array. Returns when the array is full or when the data source has no more data. The return value is the number of bytes or -1 when no more data is available.

int read(byte dest[], int offset, int length) throws IOException Just like the earlier read(byte dest[]), but only attempts to read length bytes into the portion of the byte array beginning at offset. Returns -1 at the end of the input of the number of bytes read when not at the end.

void close() throws IOException Releases system resources associated with the data source. For example, on a Unix platform, a file-input stream consumes one file descriptor. The close() call releases this file descriptor, and the stream then becomes permanently unavailable for reading.

int available() throws IOException Returns the number of bytes that may be read immediately without blocking.  This call is not reliable on all systems; some implementations of Java are known to return 0.

long skip(long nbytes) throws IOException Attempts to skip over and discard nbytes bytes from the data source. Skips fewer bytes if no more data is available. Returns the number of bytes skipped.

boolean markSupported() Returns true if the mark/rest mechanism is supported; otherwise, returns false.

void mark(int readLimit) Sets a mar in the input stream. If in the future a reset() call is made and the mark supported() is true, subsequent reads from the input stream will repeat all bytes read since the mark() call. If more than readLimit bytes are read before the next reset() call, the mark is lost.

void reset() throws IOException Repositions the stream so that subsequent reads repeat the values read since the last mark() call. Throws IOException if the file has not been, marked.

See also: