Methods of InputStream

The InputStream class provides different methods that are implemented by its subclasses. Here are some of the commonly used methods:

  1. read() - reads one byte of data from the input stream.
  2. read(byte[] array) - reads bytes from the stream and stores in the specified array.
  3. available() - returns the number of bytes available in the input stream.
  4. mark() - marks the position in the input stream up to which data has been read.
  5. reset() - returns the control to the point in the stream where the mark was set.
  6. markSupported() - checks if the mark() and reset() method is supported in the stream.
  7. skips() - skips and discards the specified number of bytes from the input stream.
  8. close() - closes the input stream.

Here is how we can implement InputStream using the FileInputStream class. Suppose we have a file named input.txt with the following content.


\begin{lstlisting}
This is a line of text inside the file.
\end{lstlisting}

Let’s try to read this file using FileInputStream (a subclass of InputStream).


\begin{lstlisting}
import java.io.FileInputStream;
import java.io.InputStream;
...
...ose() ;
}
catch ( Exception e) {
e.getStackTrace() ;
}
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Available bytes in the file : 35
Data read from the file :
This is a line of text inside the file
\end{lstlisting}