How to read integers from a file using BufferedReader 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 known as readLine() which reads and returns the next line from the source and returns it in String format.

The BufferedReader class doesn’t provide any direct method to read an integer from the user you need to rely on the readLine() method to read integers too. i.e. Initially you need to read the integers in string format.

The parseInt() method of the Integer class accepts a String value, parses it as a signed decimal integer and returns it.

Using this convert the read Sting value into integer and use. In short, to read integer value-form user using BufferedReader class −

  • 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 integer value from the current reader as String using the readLine() method.

  • Then parse the read String into an integer using the parseInt() method of the Integer class.

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 10-Sep-2019 15:24:20
Advertisements