JavaXT

How To Prompt a User for a Username and Password

Here's a simple little command line app used to prompt a user for a username and password.

package com.example;

public class Main {

    public static void main(String[] args) throws Exception {

        java.io.Console console = System.console();
        String username = console.readLine("Username: ");
        String password = new String(console.readPassword("Password: "));
        System.out.println(username+"/"+password);
    }
}

Note that this method relies on the java.io.Console class which was introduced in Java 1.6. For older versions of Java, you will need to do something like this:

package com.example;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    
    public static void main(String[] args) {
        String username = getUserName("Username: ");
        String password = getPassword("Password: ");
        System.out.println(username+"/"+password);        
    }   


    private static String getUserName(String prompt){
        String username = null;
        System.out.print(prompt);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            username = br.readLine();
        } 
        catch (IOException e) {
            System.out.println("Error trying to read your name!");
            System.exit(1);
        }
        return username;
    }


    private static String getPassword(String prompt) {

        String password = "";
        ConsoleEraser consoleEraser = new ConsoleEraser();
        System.out.print(prompt);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        consoleEraser.start();
        try {
            password = in.readLine();
        }
        catch (IOException e){
            System.out.println("Error trying to read your password!");
            System.exit(1);
        }

        consoleEraser.halt();
        System.out.print("\b");

        return password;
    }


    private static class ConsoleEraser extends Thread {
        private boolean running = true;
        public void run() {
            while (running) {
                System.out.print("\b ");
                try {
                    Thread.currentThread().sleep(1);
                }
                catch(InterruptedException e) {
                    break;
                }
            }
        }
        public synchronized void halt() {
            running = false;
        }
    }
}

References