如何打印错误信息到标准错误? [英] How to print an error message to standard error?
问题描述
在UNIX,我应该写一个Java文件,将打印出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);
这是什么,我该怎么办?
Is this what I'm supposed to do?
如果是这样,我怎么在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?
推荐答案
每个程序有三个流:
- 标准输入(
标准输入
),它通常来自键盘。您可以访问它与System.in
- 标准输出(
标准输出
),通常去到控制台。您访问它的System.out
- 标准误差(
标准错误
),通常还要到控制台。你与访问
System.err的
- Standard input (
stdin
), which normally comes from the keyboard. You access it withSystem.in
- Standard out (
stdout
), which normally goes to the console. You access it withSystem.out
- Standard error (
stderr
), which normally also goes to the console. You access it withSystem.err
在一般情况下,你的程序是正确的。它打印到标准错误
,但在正常情况下,标准错误
流到控制台(就像标准输出
流)。
In general, your program is correct. It does print to stderr
, but in normal cases, the stderr
stream goes to the console(just like the stdout
stream).
但是,你应该使用的原因标准错误
中的错误消息,而不是标准输出
的是让你可以重定向的它。这意味着你标准错误
的输出发送到文件而不是控制台。例如,你可以做到这一点庆典
:
However, the reason that you should use stderr
instead of stdout
for error messages is so that you can redirect it. That means that you send the output of stderr
to a file instead of the console. For example, you can do this in bash
:
java Program 2> errors.txt
现在,所有的 System.err.println()来
的会去一个文件,而不是在屏幕上,它可以与调试的帮助。
Now, all of the System.err.println()
's will go to a file instead of to the screen, which can help with debugging.
这篇关于如何打印错误信息到标准错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!