Table of Contents

Java Stream Class

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the basic stream classes in Java.

Why we need Stream classes?

To perform read and write operations on binary files we need a mechanism to read that binary data on file/to write binary data (i.e. in the form of byte). These classes are capable to read and write one byte on binary files. That’s why we use Stream Classes.

Types of streams:

  1. Byte Stream : It provides a convenient means for handling input and output of byte.
  2. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

1. Byte Stream:

Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream.

  • InputStream Classes - These classes are subclasses of an abstract class, InputStream and they are used to read bytes from a source(file, memory or console).
  • OutputStream Classes - These classes are subclasses of an abstract class, OutputStream and they are used to write bytes to a destination(file, memory or console).

2. Character Stream:

Character stream is also defined by using two abstract classes at the top of the hierarchy, they are Reader and Writer. These two abstract classes have several concrete classes that handle Unicode characters.

  • Reader classes : Abstract class that define character stream input.
  • Writer classes : Abstract class that define character stream output.

Example:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputStreamExample {
  public static void main(String args[]) throws IOException {
     //Creating an BufferedInputStream object
     BufferedInputStream inputStream = new BufferedInputStream(System.in);
     byte bytes[] = new byte[1024];
     System.out.println("Enter your data ");
     //Reading data from key-board
     inputStream.read(bytes);
     //Creating BufferedOutputStream object
     FileOutputStream out= new FileOutputStream("D:/sample.txt");// writer file
     BufferedOutputStream outputStream = new BufferedOutputStream(out);
     //Writing data to the file
     outputStream.write(bytes);
     outputStream.flush();
     System.out.println("Data successfully written in the specified file");
  }
}
/*OUTPUT:
Enter your data
Hi welcome to Java
Data successfully written in the specified file   */

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?