Java通过终端执行外部程序 [英] Execute external program through terminal in Java

查看:22
本文介绍了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"文件必须与 otter 可执行文件在同一个文件中.

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??

提前致谢,塔玛什

推荐答案

这是正常现象:您正在尝试启动通常由 shell 发出的命令.

This is normal: you are attempting to launch a command normally issued by a shell.

这里,>proof.out 被当作 otter 可执行文件的文字参数,而不是 shell重定向.但是看到这个工具的主页,它不起作用:它需要标准输入上的数据,重定向通常提供.

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.

您需要通过 shell 启动此命令,最好使用进程构建器:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆