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
403 views
in Technique[技术] by (71.8m points)

exec - Running external program with redirected stdin and stdout from Java

I'm trying to running an external program from a Java program and I'm having trouble. Basically what I'd like to do would be this:

 Runtime.getRuntime().exec("./extprogram <fileIn >fileOut");

However I've found that that doesn't work - Java apparentls needs to use a Process with input and output streams and other things which I'm not experienced with.

I've looked at a number of examples across the internet (many of which are from SO), and there doesn't seem to be a simple standard way of doing this, which for someone who doesn't fully understand what's going on, can be quite frustrating.

I'm also having trouble trying to build my own code off the examples of other people's code because generally it seems most other people 1. aren't interested in redirecting stdin, and 2. aren't necessarily redirecting stdout to a file, but instead to System.out.

So, would anyone be able to point me in the direction of any good simple code templates for calling external programs and redirecting stdin and stdout? Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could try something like this:

ProcessBuilder pb = new ProcessBuilder();
pb.redirectInput(new FileInputStream(new File(infile));
pb.redirectOutput(new FileOutputStream(new File(outfile));
pb.command(cmd);
pb.start().waitFor();

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

...