You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We shall lookk at the java.io.Console class which is an evolved form of the System.in/System.out methods,
🟥 8.4.1 The Old Way
Suppose we want to obtain input from the user
We need to use System.in and wrap it with InputStreamReader class
We then use BufferedReader so that the user can enter multiple characters and use termination (enter):
try (BufferedReaderreader = newBufferedReader(newInputStreamReader(System.in))) {
System.out.println("Write something:");
StringuserInput = reader.readLine();
System.out.println("This is what you wrote: "+userInput);
} catch (IOExceptione) {
}
Running the program:
🟥 8.4.2 The New Way
Java 6 introduced java.io.Console which is a singleton which is accessed using System.console() - this can potentially return null
Here is the previous program rewritten:
Consoleconsole = System.console();
if (console!=null) {
System.out.println("Write something:");
StringuserInput = console.readLine();
System.out.println("This is what you wrote: "+userInput);
}
🟡 reader() and writer()
The Console instance can also give us an instance of Reader and PrintWriter:
We can use the format(String, Objects...) method directly. This method only has one signature which does NOT take a locale variable
publicclassConsoleSamplePrint {
publicstaticvoidmain(String[] args) throwsNumberFormatException, IOException {
Consoleconsole = System.console();
if (console == null) {
thrownewRuntimeException();
} else {
console.writer().println("Welcome to Our Zoo!");
console.format("Our zoo has %f animals and employs %f people.",201, 25);
}
}
}
🟡 flush()
The flush() method forces all buffered output to be written immediately. This ensures no data is lost when calling readLine() or readPassword()
Failure to call this method can result in no text pormpt before obtaining user input.
🟡 readLine()
This method takes user input terminated by the enter key
We also have an overloaded method which displays formatted text before reading input readLine(String format, Objects...)
Consoleconsole = System.console();
console.writer().println("Enter your name: ");
StringuserName = console.readLine();
console.format("Hi %s, your name has %d characters", userName, userName.length());
/* Enter your name: shiv Hi shiv, your name has 4 characters*/
🟡 readPassword()
This method is likek readLine, except it will not echo the text the user is typing
This method returns a char[] instead of string, because this can be garbage collected rather than kept in String pool
Consoleconsole = System.console();
if (console == null) {
thrownewRuntimeException("Console unavailable");
} else {
char[] password = console.readPassword("Enter your password: ");
// immediately clear password from memoryfor (inti=0;i<password.length;i++)
password[i]='x';
}