We can read Java’s input from “System.in” console, there are two common ways to read input from console.

1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5

InputStreamReader , BufferedReader example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class ReadConsoleSystem {
  public static void main(String[] args) {
 
	System.out.println("Enter something here : ");
 
	try{
	    BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
	    String s = bufferRead.readLine();
 
	    System.out.println(s);
	}
	catch(IOException e)
	{
		e.printStackTrace();
	}
 
  }
}

Scanner example

import java.util.Scanner;
 
public class ReadConsoleScanner {
  public static void main(String[] args) {
 
	  System.out.println("Enter something here : ");
 
	   String sWhatever;
 
       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();
 
       scanIn.close();            
       System.out.println(sWhatever);
  }
}

BufferedReader or Scanner

Which one is better? Should we go for BufferedReader or Scanner? I will go for BufferedReader for one reason, i familiar with it :). Well Scanner is a new class since JDK1.5, it’s come out more easy way to read input from file, and code is more clean. I may use Scanner class in my future project ~

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts