3.8 Reading and Writing Console
3.8 Reading and Writing Console
There are 3 ways for reading input from users in the command line environment.
Advantages:
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
INPUT : GEEK
OUTPUT: GEEK
● The main purpose of scanner class is to parse primitive types and strings using regular
expressions.
● It can be also used to read input from the user in the command line.
Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
Drawback:
The reading methods are not synchronized.
Example
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
int a = in.nextInt();
float b = in.nextFloat();
Output:
Geeksforgreeks 12 3.4
You entered String :Greeksforgreeks
You entered Integer:12
You entered float:3.4
● Preferred way for reading user’s input from the command line.
● It can be used for reading password-like input without echoing the characters entered by the user;
● The format string syntax can also be used (like System.out.printf()).
Advantages:
● The input is buffered for efficient reading. Reading password without echoing the entered
characters.
Drawback:
Does not work in non-interactive environments (such as in an IDE).
String text=System.console().readLine();
Method Description
Reader reader() It is used to retrieve the reader object associated
with the console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single
line of text from the console.
char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the
args) password that is not being displayed on the console.
Console format(String fmt, Object... args) It is used to write a formatted string to the console
output stream.
Console printf(String format, Object... args) It is used to write a string to the console output
stream.
System class provides a static method console() that returns the singleton instance of Console class.
Console c=System.console();
Java Console
Example:
import java.io.Console;
class ReadStringTest
Console c=System.console();
System.out.println("Welcome "+n);
Example
System.out.println(name);
}
Java Console Example to read password
import java.io.Console;
class ReadPasswordTest
Console c=System.console();
char[] ch=c.readPassword();