问题
I was reading about Console
class, and in the very first line, it was written
New to Java 6 and when we are running
Java SE 6
from command line, then we are typically using console class object
So, which means we are implicitly using console class through the command line ??
Then, I started looking for more detail about Console class and I found Input from console class in java and Console link. So, concluded some points
- Console class are only usable outside the IDE using
System.console().readLine();
Console
class reads a password or passphrase from the console with echoing disabled usingreadPassword()
Although, we had Scanner class and BufferedReader class to read the input from console and that was added earlier than Java 5
. So, only due to security reason Console
class was added in Java 6
? or are there any other advantage(s) to use this class.
Could anyone share more details about Console
class ?
回答1:
The Console class reads directly from the process console (usually /dev/console in Unix systems). The console differs from System.in in that it cannot be redirected when a command is launched. It is also used to read passwords because reading from the console you can control whether or not you echo the chars being typed.
To clarify more on this class, read about console and standard input in Unix systems (this is typically a Unix thing and I'm not really sure how it maps to Windows systems).
Finally, Scanner can read from any input: a file, an stream, or the console itself so it's different from Console.
回答2:
The Console class tries to implement a platform independent way to handle with console input. All OS has a console in any way, but they are quiet diferent in implementation. So Console class gives you a Java platfrom independent runtime class to access things like password input, etc.
回答3:
Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
How To Get Input From Console Class In Java?
来源:https://stackoverflow.com/questions/14039762/when-should-we-use-console-class