Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

linux - Execute external program through terminal in Java

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

The "proof.in" file must be in the same file as the otter executable.

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")

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

Thanks in advance, Tamash

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is normal: you are attempting to launch a command normally issued by a 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.

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();

etc etc.

You should also ensure, of course, that the program runs from the correct directory -- fortunately, ProcessBuilder also allows you to do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...