Just a quick one here.
What are the benefits of using java.io.Console
as opposed to using a BufferedReader
wrapping an InputStreamReader
for System.in
?
Why would I use it?
Thanks for any advice!
Just a quick one here.
What are the benefits of using java.io.Console
as opposed to using a BufferedReader
wrapping an InputStreamReader
for System.in
?
Why would I use it?
Thanks for any advice!
java.io.Console
is used to take and read input from the user at runtime and output are displayed after processing the input from user.For more and detailed information visit https://www.examsmyantra.com/article/58/java/java-io---console-input-and-output
Another trick I'm pretty sure you won't get with Console--I created my own input and output streams and replaced System.in/out with them. My implementation of the stream appended to a log file as well as echoing to the screen.
When I turned on my poor-man's "Debug Info", I could even have it tell me what program/line the sysout came from (It was slow though. It created an exception and examined the appropriate stack entry so it was off by default)
java.io.Console only works when you start a Java program from a command line without redirecting STDIN/STDOUT.
The main advantage I see with Console over System.in is that you have the readPassword() method, which won't echo the characters typed by the user (I couldn't find a way to do this with System.in).
You also have readLine() which will present a prompt and read a single line. You don't have to create your own LineNumberReader.
But, if you want your Java program to be able to read from STDIN when it's redirected from a file or pipe, you still have to use System.in.
You can use
java.io.Console
to present an interactive command-line to the user. You could do all that withSystem.in
yourself, but you would have to implement things like noticing when the input was done, orreadPassword
, etc.See java.io.Console is finally here!
Because it's code that is already written for you...no need to re-invent the wheel. Chances are, you're not going to get it any better than it already is.