Java I/O How to - Prompt Password input








Question

We would like to know how to prompt Password input.

Answer

//www.j  av  a  2  s .  c  o  m
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.out.println("Console is not available");
      System.exit(1);
    }

    char[] password = "java2s.com".toCharArray();

    char[] passwordEntered = console.readPassword("Enter password: ");

    if (Arrays.equals(password, passwordEntered)) {
      System.out.println("\n Access granted \n");
      Arrays.fill(password, ' ');
      Arrays.fill(passwordEntered, ' ');
      System.out.println("OK ...");
    } else {
      System.out.println("Access denied");
      System.exit(1);
    }
  }
}

The code above generates the following result.