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!
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.
You can use java.io.Console
to present an interactive command-line to the user. You could do all that with System.in
yourself, but you would have to implement things like noticing when the input was done, or readPassword
, etc.
See java.io.Console is finally here!
One of the most popular feature requests for J2SE in recent times has been the request to improve console support and provide a way to enter passwords with echo disabled. Developers know this feature 4050435 as it has been skulking in the Top 25 RFEs list for some time.
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.
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)