我正在运行来自另一个jar的jar文件,例如here somebody answers,但正在等待该过程。
Process proc = Runtime.getRuntime().exec("java -jar A.jar" + stringParams);
try {
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
当我对所调用的程序的状态没有反馈时,我的问题就来了,但我不希望我的程序继续超出这些行。我需要标准和错误输出,但执行结束时会显示结果。在jar仍在运行时,有没有办法执行和获取这些流?
答案 0 :(得分:1)
缓冲输出似乎是一个问题。
执行过程(在这种情况下为java -jar <path>
)缓冲输出并仅在完成后写入(在大块中,我们不喜欢它!)
因此,一种方法是通过不缓冲(非常黑客的工具)执行流程:
unbuffered <command>
stdbuf -i0 -o0 -e0 <command>
stdbuf
是GNU工具的一部分。
https://www.gnu.org/software/coreutils/manual/html_node/stdbuf-invocation.html
unbuffered
是expect
包的一部分。
关键是让程序认为它处于交互模式(就像你从控制台启动它一样)。
前两个选项非常hacky并且在所有情况下都不起作用(如果java命令与它们一起使用,则为idk吗?)
第三种选择最有希望。 我们启动了一个模拟交互式终端制作程序的程序(终端模拟器),认为它在真正的活动会话中工作!
您也可以使用pty4j
:
从那里:https://github.com/traff/pty4j
// The command to run in a PTY...
String[] cmd = { "java", "-jar", "path_to_jar" };
// The initial environment to pass to the PTY child process...
String[] env = { "TERM=xterm" };
PtyProcess pty = PtyProcess.exec(cmd, env);
OutputStream os = pty.getOutputStream();
InputStream is = pty.getInputStream();
// ... work with the streams ...
// wait until the PTY child process terminates...
int result = pty.waitFor();
// free up resources.
pty.close();
也许值得尝试zt-exec
?
我不知道它是如何执行命令的。
但可能是它(我没有测试过)。
使用https://github.com/zeroturnaround/zt-exec
new ProcessExecutor().command("java", "-jar path_to_jar") .redirectOutput(new LogOutputStream() { @Override protected void processLine(String line) { ... } }) .execute();
这应该有效,但我没有测试过。 一般来说,没有办法很好地解决你的问题。
根据您要定位的平台,考虑使用unbuffered
,stdbuff
或(最慢)终端仿真......
如果有帮助并祝你好运,请告诉我! :)