由于公共字段,使用 System.out
(和相关的)总是看起来很尴尬,现在使用最新的 Netbeans 给出了一个明显的应该删除语句"提示.
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.
因此我的问题是:System.out
仍然是写入控制台的首选方式,还是应该首选其他 API?
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?
我不希望它用于日志记录,而是用于简单的控制台应用程序.ps
之类的东西,将正在运行的进程打印到控制台.
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.
在设计为从命令行运行的命令中,使用 System.out
和System.err
用于输出,以及用户可以合理期望理解的错误消息.如果您从一个体面的 shell 或脚本运行您的应用程序,System.out
和/或 System.err
流可能会被重定向到文件或管道中的另一个进程,但这是用户的选择.
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.
在 JDK 1.6 及更高版本中,java.io.Console
让您的应用程序可以访问控制台.Javadoc 中没有详细说明,但我怀疑 java.io.Console
会向控制台打开一个新流,因此无法重定向.(道德上等同于在老式 UNIX 机器上打开/dev/tty".)如果您的应用程序想要确保它正在与用户交谈,而没有任何重定向的可能性,您应该只使用它;例如请求和读取密码时.
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.
但是请注意,Console
不能保证正常工作.事实上,据观察,当您从 Eclipse ... 以及可能的其他 IDE 运行应用程序时,它不起作用.
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.
但是,如果您的应用程序是 GUI 命令,特别是如果它打算作为无人值守的服务运行,您应该避免写入控制台",因为:
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}
或 java.io.Console
)可能没有连接,或者System.{out,err}
or java.io.Console
) may be connected to nothing, or1 - 根据控制台输出的性质,这实际上可能正是用户想要的.但是应用程序员需要考虑到这一点.
这篇关于Java 控制台应用程序:System.out 是否仍然可行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!