Pages

Reading Input from Console | Java

In java, for reading the input from console, there are two options.

  1. Scanner
  2. BufferedReader
There are however some basic differences in the use of them.

Scanners treat the given input as tokens(can tokenize the input using regex). It provides methods like
nextInt()
and
next()
and so it support parsing capabilities. A bufferedReader however is not capable of this and can only read the characters from an inputStream and store as string to the buffer.

Scanners are a little bit slower then bufferedReader.

BufferedReaders are synchronized but Scanners are not. If the scanners are to be used in multiple threads, synchronization should be done manually.

Scanner has a little buffer(1kB) compared to BufferedReader(8kB).

A BufferedReader could be passed to the scanner as the source of characters to parse.

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a line");
        
        //String next = scanner.next();
        String text;
        
        while(( text = scanner.next())!= null){//
            System.out.println(text);
        }
    }

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...