Java I/O How to - Read line from Console via Console.readLine method








Question

We would like to know how to read line from Console via Console.readLine method.

Answer

/*  w w  w. jav  a  2  s. c o  m*/
import java.io.Console;
import java.sql.SQLException;

public class Main {
  public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Console console = System.console();
    if (console == null) {
      System.err.println("sales: unable to obtain console");
      return;
    }

    String username = console.readLine("Enter username: ");
    System.out.println(username);
  }
}

The code above generates the following result.