How can I apply input redirection to Javas ProcessBuilder?
E.g. use cat of Linux
cat x.txt > output.txt
My code
// read x.txt with cat and redirect the output to output.txt
public static void main (String args []) throws Exception
{
List <String> params = new ArrayList <String> ();
params.add ("cat");
params.add ("x.txt");
ProcessBuilder pb = new ProcessBuilder (params);
pb.redirectOutput (new File ("output.txt"));
Process p = pb.start ();
p.waitFor (3, TimeUnit.SECONDS);
System.out.println ("exit="+p.exitValue());
}
That works fine!
But how to change from file to input-redirection?
cat << END > output
I tried this – but does not work.
public static void main (String args []) throws Exception
{
List <String> params = new ArrayList <String> ();
params.add ("cat");
params.add ("/dev/stdin");
params.add ("<<";
params.add ("END");
ProcessBuilder pb = new ProcessBuilder (params);
pb.redirectOutput (new File ("output.txt"));
Process p = pb.start ();
OutputStream os = p.getOutputStream ();
os.write ("\nblabla\nEND\n".getBytes ());
p.waitFor (3, TimeUnit.SECONDS);
System.out.println ("exit="+p.exitValue());
}
No matter what I tried it returned with 1 (instead of 0 for success) or did not finish.
<< END
is shell syntax. The linecat << END > output
would be followed by some text followed by a lineEND
in a shell script or as input (stdin
) for a shell. Where do you want the input to come from when running a process from your Java program?