通过Java终端通过外部程序执行 [英] Execute external program through terminal in Java
问题描述
我有一个外部程序 Otter 作为参数获取了一些文件名并创建了一个输出文件,也指定为参数. 因此,例如,如果我的输入是"proof.in",并且我希望将输出放置在"proof.out"文件中,则可以在终端中运行以下命令:
I have an external program Otter that gets as parameter some filename and creates an output file, also specified as parameter. So for example if my input is "proof.in" and I want my output to be placed in the "proof.out" file, I run the following command in the terminal:
otter <proof.in >proof.out
"proof.in"文件必须与水獭可执行文件位于同一文件中.
The "proof.in" file must be in the same file as the otter executable.
问题是我需要Java提供此功能,因此在Java代码中,我需要执行以下操作:
The problem is that I need this functionality from Java so in my Java code I do the following:
java.lang.Runtime.getRuntime().exec("otter <proof.in >proof.out")
但是在这一行之后,整个UI被冻结,什么也没有发生,并且没有生成输出文件.
but after this line the whole UI is frozen and nothing happens and no output file is generated.
有人可以告诉我我错了吗?
Could anyone show me where I got it wrong??
预先感谢, 塔玛什(Tamash)
Thanks in advance, Tamash
推荐答案
这是正常现象:您正在尝试启动通常由Shell发出的命令.
This is normal: you are attempting to launch a command normally issued by a shell.
在这里,<proof.in
和>proof.out
被当作otter
可执行文件的原义参数,而不是shell重定向.但是查看该工具的主页将无法正常工作:它需要标准重定向上通常提供的stdin上的数据.
Here, <proof.in
and >proof.out
are taken as literal arguments to the otter
executable, and not shell redirections. But seeing the home page for this tool, it will not work: it expects data on stdin, which the redirect normally provides.
您需要通过外壳(最好使用流程构建器)启动此命令:
You need to launch this command via a shell, and preferably using a process builder:
final ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "otter <proof.in >proof.out");
final Process p = pb.start();
等等等
当然,您还应该确保程序从正确的目录运行-幸运的是,ProcessBuilder
也允许您执行此操作.
You should also ensure, of course, that the program runs from the correct directory -- fortunately, ProcessBuilder
also allows you to do that.
这篇关于通过Java终端通过外部程序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!