~/error.txt error.txt 填充了版本。 让我们尝试重定向标准输出: java -version > ~/o-6ren">
gpt4 book ai didi

java - 为什么 "java -version"将其输出打印到错误流?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:15:34 24 4
gpt4 key购买 nike

让我们尝试重定向 java 的标准错误:

java -version 2> ~/error.txt

error.txt 填充了版本。

让我们尝试重定向标准输出:

java -version > ~/output.txt

output.txt 为空。

为什么 java 二进制打印正常输出到错误流?

最佳答案

根据 the Java documentation :

-showversion

Displays version information and continues execution of the application. This option is equivalent to the -version option except that the latter instructs the JVM to exit after displaying version information.

-version

Displays version information and then exits. This option is equivalent to the -showversion option except that the latter does not instruct the JVM to exit after displaying version information.

现在考虑 Wikipedia's definition of stderr :

Standard error is another output stream typically used by programs to output error messages or diagnostics.

大多数以 POSIX 为中心的工具都为其标准输出流规定了非常谨慎的规范,因此该工具的输出可以通过管道传输到其他地方。 Stderr 的规定要少得多,并且可以自由地用于日志记录和错误。

通过 -showversion,Java 允许在运行的应用程序旁边打印版本信息。但是,如果版本信息被打印到 stdout,它与 可能 伴随的正常应用程序输出将无法区分,迫使您扫描并删除该行输出你自己。当然,使用 -version 而不是 -showversion,版本字符串很可能 是预期的输出,但保持一致性是一个体面的结局本身。

物有所值,printing requested metadata to stderr vs stdout is something of an open question ,因此除了每个应用程序记录的行为外,几乎没有“标准做法”。

要解决这个问题,只需将 stderr 重定向到 stdout:

VERSION=$(java -version 2>&1)

关于java - 为什么 "java -version"将其输出打印到错误流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com