tags:

views:

131

answers:

3

I'm trying out the Runtime.exec() method to run a command line process.

I wrote this sample code, which runs without problems but doesn't produce a file at c:\tmp.txt.

String cmdLine = "echo foo > c:\\tmp.txt";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmdLine);

BufferedReader input = new BufferedReader(
                           new InputStreamReader(pr.getInputStream()));
String line;

StringBuilder output = new StringBuilder();
while ((line = input.readLine()) != null) {
    output.append(line);
}

int exitVal = pr.waitFor();

logger.info(String.format("Ran command '%s', got exit code %d, output:\n%s", cmdLine, exitVal, output));

The output is

INFO 21-04 20:02:03,024 - Ran command 'echo foo > c:\tmp.txt', got exit code 0, output: foo > c:\tmp.txt

+5  A: 

echo is not a standalone command under Windows, but embedded in cmd.exe.

I believe you need to invoke a command like "cmd.exe /C echo ...".

Thorbjørn Ravn Andersen
That's not the problem, as the exit code is 0 (meaning success), the problem is that the file redirection (the `>`) is handled by the shell/cmd.exe and therefore isn't applied. The solution still is the same, however.
Joachim Sauer
+3  A: 

The > is intrepreted by the shell, when echo is run in the cmmand line, and it's the shell who create the file.

When you use it from Java, there is no shell, and what the command sees as argument is :

"foo > c:\tmp.txt"

( Which you can confirm, from the execution output )

OscarRyz
A: 

You can't just pass "> c:\tmp.txt" to Runtime.exec as part of the command line to make redirection happen. From the Javadocs: "All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream())."

If you want to redirect output to a file, to the best of my knowledge the only way to do that would be to open the file in Java, do getInputStream, and then read from the process's input stream and write to the desired file.

Jay