0

What advantages does InputStreamReader have over Scanner class?

Scanner seems better to me in all aspects.

Why do I have to use throws IOException with InputStreamReader?

For example:-

1)

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

2)

Scanner sc=new Scanner(System.in);

What is something that 1) can do and 2) cannot?

Dasyud
  • 23
  • 8

1 Answers1

0

When using Buffered reader we need to import java.io package so we need to handle exception either by try and catch or by using throws Exception. There is one disadvantage of using Scanner class when we use nextLine after nextInt: it does not read values and the output is different from the expected output

//example scanner

import java.util.Scanner; 

public class c 

{

    public static void main(String args[]) 

    {

        Scanner scn = new Scanner(System.in); 

        System.out.println("Enter an integer"); 

        int a = scn.nextInt(); 

        System.out.println("Enter a String"); 

        String b = scn.nextLine(); 

        System.out.printf("You have entered:- "+ a + " " + "and name as " + b);

    } 


}

Input: 2,rajat

Expected output: You have entered:-2 and name as rajat

Actual output: You have entered:-2 and name as

It does not take rajat in string b whereas there is no such problem with BufferReader class

//example Buffered Reader

import java.io.*; 

class c

{

    public static void main(String args[]) throws IOException 

    { 

        BufferedReader br = new BufferedReader(new

        InputStreamReader(System.in)); 

        System.out.println("Enter an integer"); 

        int a = Integer.parseInt(br.readLine()); 

        System.out.println("Enter a String"); 

        String b = br.readLine(); 

        System.out.printf("You have entered:- " + a + " and name as " + b); 

    }

}

Input 2,rajat

Expected output: You have entered:-2 and name as rajat

Actual output: You have entered:-2 and name as rajat

BSMP
  • 4,596
  • 8
  • 33
  • 44
Rajat Agrawal
  • 141
  • 1
  • 4
  • 13
  • Why is this error happening with `Scanner`? – Dasyud Oct 27 '18 at 06:03
  • I guess it is because the line is broken or already used because of integer? I added an `scn.nextLine()` and now it works normally. – Dasyud Oct 27 '18 at 06:05
  • Ok I have figure out the problem. Are there any other differences? – Dasyud Oct 27 '18 at 06:07
  • You're comparing Apples or Oranges @AdityaSoni. `InputStreamReader` just reads `char` from an `InputStream`. `Scanner` tokenizese - if you're writing an XML parser for example, you don't need tokenization, you just need the data. The answer I have linked goes into some detail about all the different methods and what they can be used for. As a general rule, `Scanner` is vastly slower because of the tokenization it does so should be avoided if you don't need it. – Boris the Spider Oct 27 '18 at 07:24