Runtime's Exec() Method Is Not Redirecting the Output

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

You need to use ProcessBuilder to redirect.

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

Redirect Runtime.getRuntime().exec() output with System.setOut();

The standard output of Runtime.exec is not automatically sent to the standard output of the caller.

Something like this aught to do - get access to the standard output of the forked process, read it and then write it out. Note that the output from the forked process is availble to the parent using the getInputStream() method of the Process instance.

public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("test.txt")));
System.out.println("HelloWorld1");

try {
String line;
Process p = Runtime.getRuntime().exec( "echo HelloWorld2" );

BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
}

Runtime.getRuntime().exec() in Java with file redirection

Changed the code to use a unix shell instead, as in the Windows solution. The resulting code looks like this:

String [] cmd = {"/bin/sh" , "-c", "/usr/local/mysql/bin/mysql -u root dev_test <div/test_db.sql"};
Process p = Runtime.getRuntime().exec(cmd);

Thanks, Joachim! Sorry for repost.

java getRuntime().exec() not working?

The command line you are using is a DOS command line in the format:

prog < input > output

The program itself is executed with no arguments:

prog

However the command from your code is executed as

prog "<" "input" ">" "output"

Possible fixes:

a) Use Java to handle the input and output files

Process process = Runtime.getRuntime().exec(command);
OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();

// Start a background thread that writes input file into "stdin" stream
...

// Read the results from "stdout" stream
...

See: Unable to read InputStream from Java Process (Runtime.getRuntime().exec() or ProcessBuilder)

b) Use cmd.exe to execute the command as is

cmd.exe /c "prog < input > output"

Capturing stdout when calling Runtime.exec

You need to capture both the std out and std err in the process. You can then write std out to a file/mail or similar.

See this article for more info, and in particular note the StreamGobbler mechanism that captures stdout/err in separate threads. This is essential to prevent blocking and is the source of numerous errors if you don't do it properly!



Related Topics



Leave a reply



Submit