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 ?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, But i want to use the password obfuscation option java console provides.
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.