«Back to Home

Core Java

Topics

How To Read Data From Keyboard In Java

Read data from keyboard

There are several ways to read data from the keyboard in Java.
Such as,
  • InputStreamReader

  • Console

  • Scanner

  • DataInputStream
InputStreamReader class

InputStreamReader class can used to read the data from the keyboard in Java.
 
It performs mainly two tasks, which are,
  1. Connects to the input stream of the keyboard.

  2. Converts the byte-oriented stream into the character-oriented stream.
BufferedReader class

BufferedReader class can be used to read the data one line by line through readLine() method.
 
Let’s see an example, given below.
 
Read the data from the keyboard by InputStreamReader and BufferdReader class.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) throws Exception {  
  4.         InputStreamReader isr = new InputStreamReader(System.in);  
  5.         BufferedReader br = new BufferedReader(isr);  
  6.         System.out.println("Please enter your name: ");  
  7.         String name = br.readLine();  
  8.         System.out.println("Hello, " + name);  
  9.     }  
  10. }  
22
 
Output

23

In the example, mentioned above, we connect the BufferedReader stream with the InputStreamReader stream to read the line by line data from the keyboard.
 
Let’s see another example, given below.
 
Read data from the keyboard by InputStreamReader and BufferdReader class, awaiting the user writes End.
 
Code
  1. import java.io.*;  
  2. public class FileHandlingExample {  
  3.     public static void main(String args[]) throws Exception {  
  4.         InputStreamReader isr = new InputStreamReader(System.in);  
  5.         BufferedReader br = new BufferedReader(isr);  
  6.         String name = "";  
  7.         while (!name.equals("End")) {  
  8.             System.out.println("Please enter your name: ");  
  9.             name = br.readLine();  
  10.             System.out.println("Your name is: " + name);  
  11.         }  
  12.         br.close();  
  13.         isr.close();  
  14.     }  
  15. }  
24

Output

25

In the example, shown above, we read and print the data until the user prints End.
 
Summary

Thus, we learnt that InputStreamReader class can be used to read the data from the keyboard and BufferedReader class can be used to read the data line by line through readLine() method in Java and also learn how to create it.