Java InputStream Class

Java InputStream Class

InputStream Class

In the Article, we will Discuss about the InputStream class of java.
In Java, the InputStream class is an abstract base class for all input streams, which represent a stream of bytes from which data can be read.

Java InputStream Class:

The InputStream Class provides a set of methods to read data from an input source, such as a file, network connection, or in-memory buffer.
The InputStream class is defined in the java.io package and contains several abstract methods, including:

Initializing a FileInputStream object:

Syntax

FileInputStream input = new FileInputStream("example.txt");

Once you have created an instance of a subclass of InputStream, you can use its methods to read data from the input source. For example, here’s how to read a single byte of data from an InputStream object:

Syntax

int data = input.read();

There are also several other methods provided by the InputStream class for marking and resetting the stream, closing the stream, and more.

InputStream is an abstract class, which means that it cannot be instantiated directly. Instead, you must use a subclass of InputStream, such as FileInputStream or ByteArrayInputStream, which provides a concrete implementation of the abstract methods.

Program to use InputStream to read data from a file:

Run
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamExample {

    public static void main(String[] args) {
        try (InputStream input = new FileInputStream("myfile.txt")) {
            int data = input.read();
            while (data != -1) {
                System.out.print((char) data);
                data = input.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

In the above example, we create a new FileInputStream object for the file “myfile.txt” and use it to create an InputStream object. We then read the first byte of data from the stream using the read() method and print it to the console as a character using a cast to char. We then continue reading bytes from the stream and printing them to the console until the end of the stream is reached (indicated by read() returning -1).

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription