Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java console applications: Is System.out still the way to go?

Tags:

java

console

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.

like image 378
Daniel Rikowski Avatar asked Mar 03 '10 08:03

Daniel Rikowski


2 Answers

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:

  • the console streams (System.{out,err} or java.io.Console) may be connected to nothing, or
  • the may user not notice the console output because the console window is buried1, or
  • the console output may end up annoying the user, especially if your application provides no way to suppress it.

1 - 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.

like image 177
Stephen C Avatar answered Oct 27 '22 19:10

Stephen C


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.

like image 22
Aaron Digulla Avatar answered Oct 27 '22 19:10

Aaron Digulla