开发者

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

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:

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


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.


I wouldn't suggest writing directly to console. By using log4j (or similiar) framework you can then configure where you want the output to go without having to change your code.


Just use a logging framework and instead of using System.out log in debug level and in your development environment (NOT production) set your output to the console and loglevel to debug

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜