4

I am trying to redirect output of a process started with the help of ProcessBuilder using following code

ProcessBuilder pb = new ProcessBuilder("/myScript >> /myLogFile 2>&1 <& - &");
Map<String, String> env = pb.environment();
env.clear();
env.put("var1", "val1");
env.put("var2", "val2");
pb.redirectErrorStream(true);
Process p = pb.start();

But it failed with exception

Exception in thread "main" java.io.IOException: Cannot run program "/myScript >> /myLogFile 2>&1 <& - &": java.io.IOException: error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)

It works fine when I just pass "/myScript"

Script is perl, any suggestions/coments on why it is failing?

I tried passing all of them as seperate arguments like new ProcessBuilder("/myScript",">>","/myLogFile"), it executes but it does not redirect to log file and also it does not take envVars.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Chandra
  • 777
  • 3
  • 12
  • 18
  • See also [How do I Pipe process output to a file on Windows](https://stackoverflow.com/questions/17089875/how-do-i-pipe-process-output-to-a-file-on-windows-and-jdk-6u45) – Vadzim Feb 07 '20 at 15:03
  • See https://stackoverflow.com/a/65649701/839733 – Abhijit Sarkar Jan 10 '21 at 02:47

2 Answers2

8

Shell redirection operators are unknown to ProcessBuilder. Put your command in a shell script and execute it, as shown here. Alternatively, use bash -c, as shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    Yeah thanks, looks like Java 7 is going to have the capability of explicitly specifying the redirection. – Chandra May 13 '11 at 02:12
1

As you specified, from Java7 you can keep using ProcessBuilder with the only executable file as parameter and redirect/intercept its output stream, using redirectInput() redirectOutput() and redirectError() from ProcessBuilder class.

Jack
  • 1,488
  • 11
  • 21