Console readLine And readPassword
System.console() may be null when the program runs without a terminal; guard it, prompt with readLine, and take secrets as char arrays from readPassword.
Code
import java.io.Console;
import java.util.Arrays;
public class InteractivePrompts {
public static void main(String[] args) {
// 无交互终端的环境(CI、cron、重定向)下 System.console() 可能返回 null
Console console = System.console();
if (console == null) {
System.out.println("no interactive console; prompt skipped");
return;
}
// readLine 可带格式化提示词,等价先 print 再读取一行
String user = console.readLine("login: ");
System.out.println("user typed: " + user);
// 密码用 readPassword:不回显,返回 char[] 而不是 String
char[] secret = console.readPassword("password: ");
System.out.println("password length: " + secret.length);
Arrays.fill(secret, (char) 0); // 用完立刻清零,避免密钥留在堆里
// format 直接写终端,不走被重定向的 stdout
console.format("welcome, %s%n", user);
}
}How it works
Everything happens inside the class InteractivePrompts and the function main.
Points of care
- It runs on exactly what the toolchain already ships — nothing extra.
Putting it to use
Entry signature: public static void main(String[] args)
The demo output is labeled (no interactive console; prompt skipped, user typed:, password length:), so each printed line points back to the operation that produced it.
Core lines
char[] secret = console.readPassword("password: ");
Arrays.fill(secret, (char) 0); // 用完立刻清零,避免密钥留在堆里
// format 直接写终端,不走被重定向的 stdout
console.format("welcome, %s%n", user);
String user = console.readLine("login: ");
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.
FAQ
- What does Console readLine And readPassword print when run?
- Running the file directly is enough — expect labeled output lines such as `no interactive console; prompt skipped`, `user typed:`, `password length:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.