Friday 26 February 2016

How to get the standard input from console in Java?

Using Scanner class:

Scanner scanner = new Scanner(System.in); String input;
while (scanner.hasNextLine()) {
     input = scanner.nextLine(); 
     System.out.println(input);
}

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 (System.in) );

String input;
while((input=br.readLine()) != null) {
     System.out.println(input);
}


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...