简体   繁体   English

如何在管道输入时让java退出

[英]How do I get java to exit when piped to head

I have a java process which prints out a lot of text. 我有一个java进程打印出很多文本。 Sometimes I just want to see a bit of the text. 有时我只是想看一些文字。 With normal programs I can just do: 使用普通程序,我可以这样做:

$ myprog | head

I'll just see 10 lines of output from myprog and it will exit immediately. 我只会看到myprog的10行输出,它会立即退出。 But with java, if I do: 但是对于java,如果我这样做:

$ java MyClass | head

I get the first 10 lines of output, but the java process won't exit until it's done with all of its processing. 我获得了前10行输出,但java进程在完成所有处理之前不会退出。 It's like java doesn't care that stdout (System.out) is gone and the head process is dead and gone. 这就像java并不关心stdout(System.out)已经消失而且头部进程已经死了。

All other programs either exit silently, like cat: 所有其他程序要么像猫一样默默地退出:

$ cat /etc/group | head
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:
news:x:9:

Or exit with a broken pipe error/exception, like python: 或者退出管道错误/异常,如python:

$ python -c 'while True: print "hi"' | head
hi
hi
hi
hi
hi
hi
hi
hi
hi
hi
Traceback (most recent call last):
  File "<string>", line 1, in <module>
IOError: [Errno 32] Broken pipe

How can get java to raise an exception when calling System.out.println() when I pipe output to something like head? 当我将输出管道输出到像head这样的东西时,如何在调用System.out.println()时让java引发异常? I'd love to be able to do something like: 我希望能够做到这样的事情:

try {
    while(true) {
        System.out.println("hi");
    }
} catch(BrokenPipeException e) {
    // exit gracefully
}

i'm using checkError() 我正在使用checkError()

From PrintStream-API-Docu : 来自PrintStream-API-Docu

Unlike other output streams, a PrintStream never throws an IOException; 与其他输出流不同,PrintStream永远不会抛出IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. 相反,异常情况只是设置一个内部标志,可以通过checkError方法进行测试。

so try somthing like this: 所以尝试这样的事情:

        while(!System.out.checkError()) {
            System.out.println("hi");
        }

If you don't like the .checkError() method from Sascha's answer and would rather receive exceptions you can use 如果您不喜欢Sascha的答案中.checkError()方法,而宁愿接收可以使用的异常

OutputStream stream = new FileOutputStream(FileDescriptor.out);

You lose the PrintStream specific functions. 您将丢失PrintStream特定的功能。 In my case, they weren't relevant and this approach was easier than building a bunch of hacky checks. 就我而言,它们并不相关,这种方法比构建一堆hacky检查更容易。

Note that this will not behave if you've redirected the System.out via System.setOut , as FileDescriptor.out will point to the original output descriptor, not your redirected one. 请注意,如果您通过System.setOut重定向System.out ,则不会出现这种情况,因为FileDescriptor.out将指向原始输出描述符,而不是重定向的描述符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM