Various ways to read from Console
When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to take some data from parent(command prompt) application. A stream object is available with us by default which is named as: System.in where by System is the class of java.lang package.
InputStream – System.in
class ISDemo { public static void main(String[] s)throws Exception { byte[] b = new byte[1024]; System.out.print("Enter Text:"); int cnt = System.in.read(b); String userString = new String(b,0,cnt); System.out.println("No. of chars: "+cnt); System.out.println("String: "+userString); } }
InputStreamReader + Systen.in
import java.io.*; class ISRDemo { public static void main(String[] s)throws Exception { InputStreamReader isr = new InputStreamReader(System.in); int data; String str = ""; char c ; while(true) { data = isr.read(); c = (char)data; if(c=='\n')break; str += c; } System.out.println("String: "+str); } }
BufferedReader + InputStreamReader + Systen.in
import java.io.*; class BufferedReaderDemo { public static void main(String[] arg)throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter text:"); String str = br.readLine(); System.out.println("String: "+str); } }
Console
import java.io.*; class ConsoleDemo { public static void main(String[] s) { Console con = System.console(); System.out.print("Enter String:"); String str = con.readLine(); System.out.println("String: "+str); } }
Scanner
import java.util.*; class ScannerDemo { public static void main(String[] arg) { Scanner sc = new Scanner(System.in); System.out.print("Enter text:"); String str = sc.nextLine(); System.out.println("String: "+str); } }
This solution has been deemed correct by the post author
Excellent material…
Was this answer helpful?
LikeDislike