📅  最后修改于: 2020-09-27 03:39:08             🧑  作者: Mango
Java Console类用于从控制台获取输入。它提供了读取文本和密码的方法。
如果您使用控制台类读取密码,则不会向用户显示该密码。
java.io.Console类在内部与系统控制台连接。从1.5开始引入Console类。
让我们看一个简单的示例,从控制台读取文本。
String text=System.console().readLine();
System.out.println("Text is: "+text);
让我们看一下Java.io.Console类的声明:
public final class Console extends Object implements Flushable
Method | Description |
---|---|
Reader reader() | It is used to retrieve the reader object associated with the console |
String readLine() | It is used to read a single line of text from 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() | It is used to read password that is not being displayed on the console. |
char[] readPassword(String fmt, Object… args) | It provides a formatted prompt then reads the 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. |
PrintWriter writer() | It is used to retrieve the PrintWriter object associated with the console. |
void flush() | It is used to flushes the console. |
系统类提供了一个静态方法console(),该方法返回Console类的单例实例。
public static Console console(){}
让我们看一下获取Console类实例的代码。
Console c=System.console();
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
输出量
Enter your name: Nakul Jain
Welcome Nakul Jain
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
输出量
Enter password:
Password is: 123