In JDK 6, the java.io.Console class is added, which allows you to obtain byte-based console devices. For example, you can obtain the Console object of the standard input and output device through the console() method added by System, and use it to perform some simple console text input and output, such as:
ConsoleDemo.java
import java.io.Console;public class ConsoleDemo { public static void main(String[] args) { System.out.print("Please enter a name:"); Console console = System.console(); String name = console.readLine(); System.out.println("The name you entered..." + name); }}Execution results:
Please enter a name: Justin
The name you entered... Justin
For password input under the main console, the Console class also provides a simple readPassword() method. When reading the password entered by the user in the main console, the bytes entered by the user will not be displayed (this was achieved in other troublesome ways in the past). For example:
ConsoleDemo.java
import java.io.Console;public class ConsoleDemo { public static void main(String[] args) { System.out.print("Please enter the name: "); Console console = System.console(); String name = console.readLine(); char[] password = console.readPassword("Please enter the password: "); System.out.println("The name you entered..." + name); System.out.println("The password you entered..." + new String(password)); }}Execution results:
Please enter a name: Justin
Please enter your password:
The name you entered... Justin
The password you entered...123456
The Console class also provides reader() and writer() methods, which can be passed back to Reader and Writer objects for other IO processing, such as using it in conjunction with Scanner:
Scanner scanner = new Scanner(System.console().reader());
It should be noted that if the application executed in javaw does not have a console (Console), the Console object cannot be retrieved (for example in Eclipse).
The above is all about the Console object instance code in Java. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!