In Java, utilizing Runtime.getRuntime().exec() to run a command allows for capturing the process's output and error streams. However, in cases where output redirection is desired, this method alone may prove ineffective.
When employing Runtime.getRuntime().exec() with commands that feature output redirection, such as
To successfully redirect output, consider utilizing ProcessBuilder instead. This class offers a more granular approach to process creation, enabling the specification of output and error stream redirection.
Here's how to use ProcessBuilder for output redirection:
ProcessBuilder builder = new ProcessBuilder("sh", "somescript.sh");
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("out.txt"));
Process p = builder.start(); // may throw IOException
By using ProcessBuilder, you can redirect both the standard output and standard error streams to the desired file, ensuring that the output from the command is captured.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3