English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about the Java InputStream class and its methods through an example.
The InputStream class in the java.io package is an abstract superclass that represents a byte input stream.
Since InputStream is an abstract class, it is not used by itself. However, its subclasses can be used to read data.
To use the InputStream functionality, we can use its subclasses. Its subclasses include:
In the next tutorial, we will learn all these subclasses.
To create an InputStream, we must first import the java.io.InputStream package. After importing the package, we can create the input stream.
// Create an InputStream InputStream object1 = new FileInputStream();
Here, we use FileInputStream to create an input stream. This is because InputStream is an abstract class. Therefore, we cannot create an InputStream object.
Note: We can also create input streams from other subclasses of InputStream.
The InputStream class provides different methods implemented by its subclasses. Here are some commonly used methods
read() - Read a byte of data from the input stream
read(byte[] array) - Read bytes from the stream and store them in the specified array
available() - Return the number of available bytes in the input stream
mark() - Mark the position of the data in the input stream
reset() -Return the control point to the point set by mark in the stream
markSupported()- Check if the stream supports mark() and reset() methods
skips() - Skip and discard the specified number of bytes in the input stream
close() - Close Input Stream
The following is the implementation of the InputStream method using FileInputStream class.
Assuming we have a file namedinput.txtwhich contains the following content.
This is a line of text in the file.
Let's try to use FileInputStream (a subclass of InputStream) to read this file.
import java.io.FileInputStream; import java.io.InputStream; public class Main { public static void main(String args[]) { byte[] array = new byte[100]; try { InputStream input = new FileInputStream("input.txt"); System.out.println("Available bytes in the file:"); + input.available()); //Read bytes from the input stream input.read(array); System.out.println("Read data from file:"); //Convert byte array to string String data = new String(array); System.out.println(data); //Close Input Stream input.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Result
Available bytes in file: 35 Data read from file: This is a line of text in the file.
In the above example, we created an input stream using the FileInputStream class. The input stream is associated with a fileinput.txtLink.
InputStream input = new FileInputStream("input.txt");
To read frominput.txtWe have implemented these two methods to read data from a file.
input.read(array); //Read Data from Input Stream input.close(); //Close Input Stream