"Using ProcessBuilder for output redirection"
P粉517090748
P粉517090748 2023-08-24 20:26:08
0
2
456
<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粉517090748
P粉517090748

reply all(2)
P粉204079743

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.

P粉818088880

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template