What is a Stream and what are the types of Streams and classes in Java?


Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc.

In general, a Stream will be an input stream or, an output stream.

  • InputStream − This is used to read data from a source.
  • OutputStream − This is used to write data to a destination.

Based on the data they handle there are two types of streams −

  • Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.
  • Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.

Following diagram illustrates all the input and output Streams (classes) in Java.

Standard Streams

In addition to above mentioned classes Java provides 3 standard streams representing the input and, output devices.

  • Standard Input − This is used to read data from user through input devices. keyboard is used as standard input stream and represented as System.in.
  • Standard Output − This is used to project data (results) to the user through output devices. A computer screen is used for standard output stream and represented as System.out.
  • Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err.

Example

Following Java program reads the data from user using BufferedInputStream and writes it into a file using BufferedOutputStream.

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:/myFile.txt");
      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 Tutorialspoint ....
Data successfully written in the specified file

Updated on: 01-Aug-2019

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements