System.err有什么意义? [英] What is the point of System.err?

查看:171
本文介绍了System.err有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UNIX中,我应该编写一个Java文件,将EXIT 1打印到标准错误,然后以状态1退出。

In UNIX, I'm supposed to write a Java file that will print "EXIT 1" to the standard error, and then exit with a status of 1.

这是我的方法..

System.err.println("EXIT 1");
System.exit(1);

这是我应该做的吗?

如果是这样,我应该如何在Unix shell中使用它?当我在bash中编译并运行它时,它只打印EXIT 1(因此它与System.out.println做同样的事情,我为什么要使用err?)。这里的标准错误是什么?

If so, how am I supposed to use it in the Unix shells? When I compile and run it in the bash, it just prints "EXIT 1" (so it does the same thing as System.out.println, why should I use "err"?). What is the "standard error" here?

推荐答案

每个正在运行的程序都有这三个流:

Every running program has these three streams:


  • 标准输入(stdin),通常来自键盘。公开为 System.in

  • 标准输出(标准输出),通常进入控制台。公开为
    System.out

  • 标准错误(stderr),通常也会进入控制台。公开为 System.err

  • Standard input (stdin), which normally comes from the keyboard. Exposed as System.in
  • Standard out (stdout), which normally goes to the console. Exposed as System.out
  • Standard error (stderr), which normally also goes to the console. Exposed as System.err

您的程序是正确的 - 它确实打印到stderr。但是在正常情况下,stderr流就像stdout流一样进入控制台,因此它们在视觉上无法区分。

Your program is correct – it does print to stderr. But under normal circumstances, the stderr stream goes to the console just like the stdout stream, so they are visually indistinguishable.

但是,你应该使用stderr而不是stdout对于错误消息,是重定向。这意味着您将stderr发送到文件而不是控制台。同时,stdout将不受影响,因为这两个流是独立的。

However, the reason you should use stderr instead of stdout for error messages, is redirection. That means that you send stderr to a file instead of the console. Meanwhile, stdout will be unaffected, because the two streams are independent.

例如,您可以在bash,cmd,PowerShell等中执行此操作:

For example, you can do this in bash, cmd, PowerShell, etc:

$ java Program 2> errors.txt

现在,所有输出 System.err.println() 将以 errors.txt 结尾,而 System.out.println()将仍然去屏幕。这有助于调试。

Now, all output with System.err.println() will end up in errors.txt, while System.out.println() will still go to the screen. This can help with debugging.

这篇关于System.err有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆