views:

754

answers:

5

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!

+7  A: 

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.

Justin Niessner
that's true! so are you saying i shouldn't develop my own linked list generic types as well for each project?! :P
Beau Martínez
+4  A: 

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.

Jared Oberhaus
erasing characters? Isn't that performed by the system console it self?
OscarRyz
If you use a BufferedReader around System.in then you don't need to "notice" the erasing of characters or any of that stuff. <code>readPassword</code> is a good reason to use Console, though.
Chochos
Thanks guys, you're right. I removed the part about erasing characters.
Jared Oberhaus
+4  A: 

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.

eed3si9n
+1  A: 

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.

Chochos
+1  A: 

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)

Bill K