BufferedReader class in Java.


The BufferedReader class of Java is used to read the stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter.

This class provides a method named read() and readLine() which reads and returns the character and next line from the source (respectively) and returns them.

  • Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.

  • Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter.

  • Now, read data from the current reader as String using the readLine() or read() method.

Example

The following Java program demonstrates how to read integer data from the user using the BufferedReader class.

 Live Demo

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Employee{
   String name;
   int id;
   int age;
   Employee(String name, int age, int id){
      this.name = name;
      this.age = age;
      this.id = id;
   }
   public void displayDetails(){
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Id: "+this.id);
   }
}
public class ReadData {
   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("Enter your age: ");
      int age = Integer.parseInt(reader.readLine());
      System.out.println("Enter your Id: ");
      int id = Integer.parseInt(reader.readLine());
      Employee std = new Employee(name, age, id);
      std.displayDetails();
   }
}

Output

Enter your name:
Krishna
Enter your age:
25
Enter your Id:
1233
Name: Krishna
Age: 25
Id: 1233
raja
Published on 12-Sep-2019 09:56:28
Advertisements