Process requires redirected input

initialZero picture initialZero · Jun 3, 2010 · Viewed 9k times · Source

I have a UNIX native executable that requires the arguments to be fed in like this

prog.exe < foo.txt.

foo.txt has two lines: bar baz

I am using java.lang.ProcessBuilder to execute this command. Unfortunately, prog.exe will only work using the redirect from a file. Is there some way I can mimic this behavior in Java?

Of course,

ProcessBuilder pb = new ProcessBuilder("prog.exe", "bar", "baz"); 

does not work.

Thanks!

Answer

Marc picture Marc · Jun 3, 2010
ProcessBuilder pb = new ProcessBuilder("prog.exe");
Process p = pb.start();
OutputStream pos = p.getOutputStream();

InputStream fis = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int read = 0;
while((read = fis.read(buffer)) != -1) {
    pos.write(buffer, 0, read);
}
fis.close();

Not tested, but something like this should work.