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.

JavaCli Tooling

Code

snippet
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

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:`.