我有一个可以打印到stdout的Java程序。例如,如果将输出通过管道传递给head
shell,那么在head完成其工作之后,shell不会立即返回,而是等待Java程序完成其所有工作。
所以我的问题是:如何编写Java程序,以便shell像一样立即返回cat ... | head
?
这是我的意思的一个例子:
在这里head
,无论有多大,shell都会立即返回,因为无需花费时间即可打印前十行bigfile.txt
:
time cat bigfile.txt | head
...
real 0m0.079s
user 0m0.001s
sys 0m0.006s
在这里,前十行会被快速打印出来,但是在处理完所有文件后,shell才会返回:
time java -jar DummyReader.jar bigfile.txt | head
...
real 0m18.720s
user 0m16.936s
sys 0m2.212s
DummyReader.jar
就这么简单:
import java.io.*;
public class DummyReader {
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new FileReader(new File(args[0])));
String line;
while((line= br.readLine()) != null){
System.out.println(line);
}
br.close();
System.exit(0);
}
}
我的设置:
java -version
java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-10M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)
在MacOS 10.6.8上
这只是因为您在println调用之后没有检查错误。这是停止的修订版本。不过,这样做会比较慢,因为checkError()会刷新到目前为止已缓冲的所有输出。
可能还有其他方法可以在不降低速度的情况下获得有关错误的通知。我已经看到一些可以显式处理SIGPIPE信号的代码,但是我不知道这是否是最好的方法。
import java.io.*;
public class DummyReader {
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new FileReader(new File(args[0])));
String line;
int linecount = 0;
while((line= br.readLine()) != null){
System.out.println(line);
if (System.out.checkError())
{
System.err.println("Got some sort of error in the output stream");
break;
}
linecount++;
}
br.close();
System.err.println("Read " + linecount + " lines.");
System.exit(0);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句