3

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 ?

halil
  • 800
  • 16
  • 33
Saar peer
  • 817
  • 6
  • 21
  • This sounds like a known bug/problem: System.console returns null. For information and possible workarounds see the answers to this question: http://stackoverflow.com/questions/4203646/system-console-returns-null – Akunosh Sep 06 '16 at 11:16

1 Answers1

0

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 Console 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/Scanner if not.

xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
chimmi
  • 2,054
  • 16
  • 30
  • Thanks, But i want to use the password obfuscation option java console provides. – Saar peer Sep 06 '16 at 12:56
  • You can keep using console if it is present and fail back to BufferedReader/Scaner if not. I dont understand how you can use 'password obfuscation option java console provides' if you have no console. – chimmi Sep 06 '16 at 13:16
  • I don't want to use BufferedReader/Scaner because then i am in a risk that the user will set the password without obfuscation. Anyway, You are probably right and there is no solution. I will add an option to send the password in a text file. – Saar peer Sep 07 '16 at 06:41