Java Console 类
最后修改时间:2025 年 4 月 16 日
java.io.Console 类提供了访问基于字符的控制台设备的方法。它主要用于在控制台应用程序中读取输入和写入输出。该类提供了密码输入和格式化输出等功能。
当程序从命令行运行时,通常会使用 Console。它提供了比 System.in 和 System.out 更方便的方法。该类在 Java 6 中引入,以简化控制台 I/O 操作。
Console 类概述
Console 类提供了用于读取输入和将输出写入控制台的方法。它支持使用 printf 进行格式化输出和安全密码输入。该类还提供对控制台的 Reader 和 Writer 对象的访问。
public final class Console implements Flushable {
public PrintWriter writer();
public Reader reader();
public Console format(String fmt, Object... args);
public Console printf(String format, Object... args);
public String readLine(String fmt, Object... args);
public String readLine();
public char[] readPassword(String fmt, Object... args);
public char[] readPassword();
public void flush();
}
上面的代码显示了 Console 提供的关键方法。这些方法允许方便的控制台 I/O 操作。该类是 final 的,不能被子类化。请注意,Console 对象是通过 System.console 方法获得的。
获取 Console 实例
使用 System.console 获得 Console 实例。如果程序未在控制台环境中运行,则此方法返回 null。在使用控制台对象之前,请务必检查是否为 null。
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
System.exit(1);
}
console.printf("Console is available\n");
String name = console.readLine("Enter your name: ");
console.printf("Hello, %s!\n", name);
}
}
此示例演示了如何获取和使用 Console 实例。程序首先检查控制台是否可用。然后,它使用控制台方法读取输入和写入输出。这在不提供控制台的 IDE 中将不起作用。
使用 Console 读取输入
readLine 方法从控制台读取单行文本。它可以在读取输入之前显示格式化的提示。如果到达流的末尾,该方法将返回 null。输入被读取为 String。
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
System.exit(1);
}
// Simple readLine
String input = console.readLine();
console.printf("You entered: %s\n", input);
// readLine with prompt
String name = console.readLine("What is your name? ");
console.printf("Hello, %s!\n", name);
// Formatted prompt
int age = Integer.parseInt(
console.readLine("How old are you, %s? ", name));
console.printf("%s is %d years old\n", name, age);
}
}
此示例显示了使用 readLine 的不同方法。第一个调用在没有提示的情况下读取输入。第二个显示一个简单的提示。第三个使用带有变量的格式化提示。请注意,必须解析数字输入。
安全地读取密码
readPassword 方法读取密码,而不会将字符回显到控制台。它返回一个 char 数组而不是 String 以确保安全。使用后应清除该数组以防止内存窥探。
import java.io.Console;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
System.exit(1);
}
char[] password = console.readPassword("Enter your password: ");
char[] confirm = console.readPassword("Confirm password: ");
if (Arrays.equals(password, confirm)) {
console.printf("Password accepted\n");
} else {
console.printf("Passwords don't match\n");
}
// Clear sensitive data from memory
Arrays.fill(password, ' ');
Arrays.fill(confirm, ' ');
}
}
此示例演示了安全密码处理。比较了两个密码输入,从未创建 String 对象。char 数组在使用后被清除。这可以防止密码在内存中停留的时间超过所需时间。
使用 Console 进行格式化输出
printf 和 format 方法提供类似于 String.format 的格式化输出。它们支持相同的格式说明符。这些方法返回 Console 对象以进行方法链。
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
System.exit(1);
}
String name = "John";
int age = 30;
double score = 85.5;
// Simple printf
console.printf("Hello, %s\n", name);
// Method chaining
console.format("Name: %s, ", name)
.format("Age: %d, ", age)
.printf("Score: %.2f\n", score);
// Complex formatting
console.printf("%-10s %5d %8.2f\n", name, age, score);
console.printf("%-10s %5d %8.2f\n", "Alice", 25, 92.3);
}
}
此示例显示了 Console 的各种格式化选项。第一个 printf 演示了简单的字符串替换。方法链显示了如何顺序调用 format/printf。最后一个示例演示了列格式化。
使用 Console 的 Reader 和 Writer
reader 和 writer 方法提供对控制台底层字符流的访问。当您需要 Reader/Writer 接口的灵活性而不是 Console 方法时,这可能很有用。
import java.io.Console;
import java.io.IOException;
import java.io.Reader;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
System.exit(1);
}
// Using the Writer
PrintWriter writer = console.writer();
writer.println("This is written using PrintWriter");
writer.printf("Formatted output: %d %f\n", 42, 3.14);
// Using the Reader
Reader reader = console.reader();
char[] buffer = new char[100];
try {
System.out.println("Enter some text:");
int count = reader.read(buffer);
console.printf("You entered: %s\n", new String(buffer, 0, count));
} catch (IOException e) {
e.printStackTrace();
}
}
}
此示例演示了使用 Console 的 Reader 和 Writer。PrintWriter 提供了熟悉的输出方法。Reader 允许更灵活的输入处理。这两个流都连接到同一个控制台设备。
来源
在本文中,我们介绍了 Java Console 类的基本方法和特性。了解这些概念对于在 Java 中构建交互式控制台应用程序至关重要。
作者
列出所有Java教程。