Q:

Java : How to read password from file?

I am using System.console() in order to read user password.
My code:
    Console console = System.console();
    if (console == null) {
        throw new RuntimeException("No console is available for input");
    }

    System.out.print("Enter the password: ");
    String password = new String(console.readPassword());

It's working fine when I am running it straightforward (from Redhat).
The problem is when I try to read the password from a text file:
java -jar my_jar.jar < password.txt
I get : 

No console is available for input.

How can I solve it ?

A:

This behaviour is expected. Quote from java.io.Console:

Whether a virtual machine has a console is dependent upon the
    underlying platform and also upon the manner in which the virtual
    machine is invoked.  If the virtual machine is started from an
    interactive command line without redirecting the standard input and
    output streams then its console will exist and will typically be
    connected to the keyboard and display from which the virtual machine
    was launched.

For a possible solution without using Cosole you can read this answer Trying to read from the console in Java.
You can keep using console if it is present and fail back to BufferedReader/Scaner if not.

