Java - File Input Output Console Class

Introduction

Console class makes the interaction between a Java program and the console easier.

Console class in the java.io package gives access to the system console.

The console is not always accessible in a Java program.

You get the instance of the Console class by using the static console() method of the System class as follows:

Console console = System.console();
if (console != null) {
        console.printf("Console is available.")
}

Console class has a printf() method that is used to display formatted string on the console.

The following code shows how to use the console class, it prints a message and the program exits.

The code uses Console Class to read User Name and Password

Demo

import java.io.Console;

public class Main {
  public static void main(String[] args) {
    Console console = System.console();
    if (console != null) {
      console.printf("Console is available.%n");
    } else {//  www  . j a  v  a2s .co  m
      System.out.println("Console is not available.%n");
      return; // A console is not available
    }

    String userName = console.readLine("User Name: ");
    char[] passChars = console.readPassword("Password: ");
    String passString = new String(passChars);
    if (passString.equals("letmein")) {
      console.printf("Hello %s", userName);
    } else {
      console.printf("Invalid password");
    }
  }
}

Result