Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Overview of Stream Classes in Java

 

In this lesson, you will learn.

  • Input/Output Streams in Java
  • Byte Stream and Character Stream
  • Predefined Streams in Java
  • Reading a Character
  • Reading a String
  • Examples

 

Input/Output Stream in Java

  • Java programs perform I/O (Input/Output) through streams.
  • I/O streams are used to read data from a source or to write data to a destination.
  • A stream is an abstraction that either produces or consumes information.
  • A stream is linked to a physical device by the Java I/O system.

 

Types of I/O Stream in Java

There are two types of streams in Java as shown below.

 

Note: Input/Output Stream Classes are defined in the java.io package.

Note: The original version of Java (Java 1.0) did not include character streams and, thus, all I/O was byte-oriented. Character streams were added by Java 1.1.

Note: At the lowest level, all I/O is still byte-oriented. The character-based streams simply provide a convenient and efficient means for handling characters.

 

The Byte Stream Classes

  • Byte streams are primarily used for handling input and output of bytes.
  • Byte streams are used, for example, when reading or writing binary data.

 

Byte Stream has two abstract classes.

InputStream Class

Used to read data from a source. It has some key classes summarized below.

 

Key Classes of InputStream:

  • FileInputStream: Reads data from a file.
  • BufferedInputStream: Adds buffering to an input stream.
  • DataInputStream: Allows reading of Java primitive data types.
  • ObjectInputStream: Used for reading objects.

 

OutputStream Class

Used to write data to a destination. It has some key classes summarized below.

 

Key Classes of OutputStream:

  • FileOutputStream: Writes data to a File.
  • BufferedOutputStream: Adds buffering to an output stream.
  • DataOutputStream: Allows writing of Java primitive data types.
  • ObjectOutputStream: Used for writing objects.

 


 

The Character Stream Classes

  • Character streams provide a convenient means for handling the input and output of characters.
  • They use Unicode and, therefore, can be internationalized.

 

The Character Stream has two abstract classes.

Reader Class

Used to read data from a source. It has some key classes summarized below.

 

Key Classes:

  • FileReader: Reads character files.
  • BufferedReader: Buffer’s characters for efficient reading.
  • InputStreamReader: Bridges byte streams to character streams.
  • StringReader: Reads characters from a string.

 

Writer Class

Used to write data to a destination. It has some key classes summarized below.

 

Key Classes:

  • FileWriter: Writes characters to a file.
  • BufferedWriter: Buffer’s characters for efficient writing.
  • OutputStreamWriter: Bridges character streams to byte streams.
  • StringWriter: Writes characters to a string.

 

The Predefined Streams

The System class (defined in java.lang package) contains three predefined stream variables: in, out, and err. These fields are declared as public, static, and final within the System.

 

1. System.out refers to the standard output stream. By default, this is the console.

2. System.in refers to standard input, which is the keyboard by default.

3. System.err refers to the standard error stream, which also is the console by default.

 

System.in is an object of type InputStream. System.out and System.err are objects of type PrintStream.

These are byte streams, even though they are typically used to read and write characters from and to the console. As you will see, you can wrap these within character-based streams, if desired.

 

2. Reading Data From a Console

InputStreamReader and BufferedReader Stream Classes are used to read data from a console.

 

The InputStreamReader Class

  • The InputStreamReader is a bridge from byte streams to character streams.
  • It reads bytes and decodes them into characters using a specified charset.

 

Syntax

InputStreamReader isr = new InputStreamReader(System.in);

 

This is usually used to read bytes from an input stream (like System.in) and convert them into characters.

System.in is a standard input stream, typically connected to keyboard input.

 

The BufferedReader Class

BufferedReader reads text from a character input stream, buffering characters and providing efficient reading of characters, arrays, and lines.

 

Syntax

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 

It buffers the input for efficient reading of characters, arrays, and lines and stores in an object br.

 

Reading a Character

The read() method is used to read character from a BufferedReader.

 

Syntax:

int read() throws IOException

It reads a character from the input stream and returns it as an integer value.

 

Example 1: Reading a Single Character

package ch3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadSingleCharacter {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader
        		(new InputStreamReader(System.in));
        System.out.println("Enter a character: ");
        int charAsInt = reader.read(); // Reads a single character
        char character = (char) charAsInt;
        System.out.println("You entered: " + character);
        reader.close();
    }
}

 

Output

First Run

Enter a character: 
A
You entered: A

 

Second Run

Enter a character: 
Hot Java
You entered: H

 

Reading Strings from a Console

The readLine() method is used to read a String from a console. It is a member of the BufferedReader class.

 

Example 1: Reading a Single String

package ch3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SingleStringInput {
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader
        		(new InputStreamReader(System.in));
            
        System.out.println("Enter your name:");
        String name = reader.readLine();
        System.out.println("Hello, " + name + "!");
    }
}

 

Output

Enter your name:
Amit Kumar
Hello, Amit Kumar!

 

Example 2: Reading Integer Input and Performing Arithmetic

package ch3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IntegerArithmetic {
    public static void main(String[] args) throws IOException
    {
    	BufferedReader reader = new BufferedReader(
    			new InputStreamReader(System.in));
    	
    	System.out.println("Enter first number:");
        int firstNumber = Integer.parseInt(reader.readLine());
        
        System.out.println("Enter second number:");
        int secondNumber = Integer.parseInt(reader.readLine());
        
        int sum = firstNumber + secondNumber;
        System.out.println("The sum is: " + sum);
    }
}

 

Output

Enter first number:
10
Enter second number:
15
The sum is: 25

 

Explanation

Integer.parseInt(String s): This static method from the Integer class attempts to parse a String as an integer value.

It throws NumberFormatException if the string cannot be parsed as an integer.

IOException: This exception is thrown when an I/O operation fails or is interrupted. In this context, it could be thrown by the readLine() method if an I/O error occurs while reading input from the user.

 

Bonus!

 

Example 4: Reading Multiple Lines Until Specific Input (e.g., “stop”)

 

package ch3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MultiLineInput {
    public static void main(String[] args) throws IOException {
    	
    	BufferedReader reader = new BufferedReader
    			(new InputStreamReader(System.in));
    	
    	String inputLine;
    	System.out.println("Enter lines of text (type 'stop' to quit):");
    	
    	while (!(inputLine = reader.readLine()).equalsIgnoreCase("stop")) 
    	{
    		System.out.println("You entered: " + inputLine);
    	}
    }
}

 

Output

Enter lines of text (type 'stop' to quit):
Java is an object oriented programming language.
You entered: Java is an object oriented programming language.
Java is simple and platform independent language.
You entered: Java is simple and platform independent language.
stop

 

 


 

Writing Console Output

  • The print() and println() methods of PrintStream are used to write on the console.
  • The PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console.

 

Syntax:

void write(int byteval)

This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written

Here is a small example of write() method to output the character ‘B’ followed by a newline.

 

Example

public class WriteExample {

	public static void main(String[] args) {
		int b = 'B';
		System.out.write(b);
		System.out.write('n');
	}
}

 

Output

B

 

The PrintWriter Class

  • PrintWriter is one of the character-based classes and can be used to write data to the console. However, using System.out to write to the console is acceptable.
  • PrintWriter supports the print( ) and println( ) methods.

 

PrintWriter defines several constructors. The one we will use is shown here.

PrintWriter(OutputStream outputStream, boolean flushingOn)

Here, outputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println( ) method (among others) is called.

If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic.

 

Example: Using PrintWriter Class

import java.io.PrintWriter;

public class PrintWriterExample {

	public static void main(String[] args) {
		PrintWriter pw = new PrintWriter(System.out, true);
		pw.println("Display output using PrintWriter class");
		int x = -17;
		pw.println(x);
		double d = 2.5e-5;
		pw.println(d);
	}
}

 

Output

Display output using PrintWriter class
-17
2.5E-5

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review