How to make Java console input disappear after pressing enter key
I am using the Scanner class to get some input from the user through the console. Whenever the user enters something on the screen and clicks, enter the input on the screen, for example:
This is a hint // User writes a command and hits enter
- Command
- the command output goes here
// Use the write3 command
- Command
- the command output goes here
- command3
- the output of command3 is here
Is there anyway I can get the entered command not to stay in the console after pressing enter?
For instance:
// User writes command
- the command output goes here
a source to share
Short answer: no, not directly inside Java. Java has very limited control over the console: you can only read and write to it. Anything displayed on the console cannot be erased by software.
Long answer: in Java, all console operations are handled through input and output streams System.in
- this is the input stream, and the System.out
u System.err
are the output streams. As you can see for yourself, there is no way to change the output stream in Java - essentially, the entire output stream does indeed output bytes to some destination (which is one of the reasons why it is called a "stream" - one way). *
The only workaround I see is using the Console
(from System.console()
) object . In particular, the method readPassword()
does not strip away all user types returned to the console. However, there are three problems with this approach. First of all, the class Console
is only available in Java 1.6. Secondly, I would not recommend using this for inputs other than passwords, as it would make the input commands more difficult than intended. And thirdly, it still does not erase the hint from the screen, which, in my opinion, will defeat the purpose of what you are trying to achieve.
* - Technically speaking, System.out
and System.err
are instances PrintStream
, but PrintStream
pretty much just the flexible version of OutputStream
-a PrintStream
is still like a normal output stream in that the output is one-way.
a source to share
It will be difficult for you to do this with the standard library.
If you don't want to do it yourself , you can do it with a third party library like JLine .
a source to share
huh - I always assumed that if you sent back characters ('\ b') to sysout it will clean up, but I never tried (don't do a lot of console programming these days).
Haven't tried it, but the bottom of this thread seems to indicate that it should work.
Please note that this may not work in the IDE console, but it may work in the normal OS console ...
I'm leaving actually proof that it works as an exercise for the OP :-)
a source to share