user2110167 user2110167 - 1 year ago 111
Java Question

Runtime's exec() method is not redirecting the output

Process p = Runtime.getRuntime().exec("sh &> out.txt");

I am running this command using Java. The script is running but it's not redirecting its stream to the file. Moreover, the file
is not getting created.

This script runs fine if I run it on shell.

Any ideas?

Answer Source

You need to use ProcessBuilder to redirect.

ProcessBuilder builder = new ProcessBuilder("sh", "");
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("out.txt"));
Process p = builder.start(); // may throw IOException
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download