Using System.out
(and related) always seemed awkward because of the public field and now with the latest Netbeans gives a blatant "Statement should be removed" hint.
Hence my question: Is System.out
still the preferred way to write to the console or is there any other API which should be preferred?
EDIT: I don't want this for logging, but for a simple console application. Something like ps
which prints out the running processes to the console.
In a command that is designed to be run from the command line, it is (IMO) reasonable to use System.out
and System.err
for output, and for error messages that the user could reasonably expect to understand. If you are running your application from a decent shell or script, the System.out
and/or System.err
streams may be redirected to files or another process in a pipeline, but this is the user's choice.
In JDK 1.6 and later, the java.io.Console
gives your application access to the console. It is not spelled out in the Javadoc, but I suspect that java.io.Console
opens a fresh stream to the console, and therefore cannot be redirected. (The moral equivalent of opening "/dev/tty" on an old-school UNIX box.) You should only use this if your application wants to to be sure it is talking to the user, without any possibility of redirection; e.g. when requesting and reading a password.
Note however, that Console
is not guaranteed to work. Indeed, it is observed that it doesn't work when you are running an application from Eclipse ... and possibly other IDEs.
However, if your application is GUI command, and particularly if it is intended to run as an unattended service, you should avoid "writing to the console" because:
System.{out,err}
or java.io.Console
) may be connected to nothing, or1 - Depending on the nature of the console output, this may actually be precisely what the user wants. But the application programmer needs to take this into account.
Yes, mostly for one reason: There is no other way to write to the console. Even if you use a logging framework, it will eventually use System.out
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With