search

Home  >  Q&A  >  body text

"Using ProcessBuilder for output redirection"

<p>I'm trying to redirect the output of a process started by ProcessBuilder using the following code: </p> <pre class="brush:php;toolbar:false;">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();</pre> <p>But it failed, throwing exception: </p> <blockquote> <p>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)</p> </blockquote> <p>When I just pass "/myScript" it works fine. </p> <p>The script is perl, any suggestions/comments on why it fails? </p> <p>I tried passing them as separate parameters like <code>new ProcessBuilder("/myScript",">>","/myLogFile")</code> and it worked, but Will not redirect to log files, nor will envVars be accepted. </p>
P粉517090748P粉517090748483 days ago460

reply all(2)I'll reply

  • P粉204079743

    P粉2040797432023-08-25 10:53:05

    According to your requirement, starting from Java7, you can continue to use ProcessBuilder, just pass the executable file as parameter and use redirectInput(), redirectOutput()# in the ProcessBuilder class ## and redirectError() to redirect/intercept its output stream.

    reply
    0
  • P粉818088880

    P粉8180888802023-08-25 10:07:03

    The

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

    reply
    0
  • Cancelreply