Friday, 26 February 2016

How to get the standard input from console in Java?

Using Scanner class:

Scanner scanner = new Scanner(; String input;
while (scanner.hasNextLine()) {
     input = scanner.nextLine(); 

scanner.close(); // Close to avoid the Resource leak.

Scanner close methods:
next, nextByte, nextShort, nextInt, nextLong, nextFloat, nextDouble.

Using InputStreamReader:

BufferedReader br = new BufferedReader(new InputStreamReader ( );

String input;
while((input=br.readLine()) != null) {

Which one should be opt?
It depends on the developer’s requirement.

For performance perspective, character by character reading from an unbuffered input stream or reader is inefficient. If the file needs to be read that way, developer should prefer BufferedReader.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...