views:

39

answers:

4
void restartWeb() {
        try {
            String[] command = new String[] {"webRestarter.exe" , ">>","webLog.log"};
            Runtime.getRuntime().exec(command);
        } catch (java.io.IOException err) {
        webServer.logError(err.getMessage());
        }
    }

Why doesn't this work? How could I fix it so it does work like I want it to?

-- Executes webRestarter.exe with parameters >>webLog.log

So it'd spit out something like this:

webRestarter.exe>>webLog.log
+1  A: 

Parameters are passed directly to the webRestarter.exe command. You can't use parameters to redirect standard output to a file, as this is usually done by your command line interpreter.

However, the exec() method returns a Process object, which you could use to retrieve standard output and write it to a file.

Sources:

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29

http://download.oracle.com/javase/6/docs/api/java/lang/Process.html

Vivien Barousse
+1  A: 

If I'm not mistaken, pipes, redirects etc are a function of a shell. In this context, these are just arguments. You could handle this as simply as using cmd.exe with a /c switch as part of your command, I believe it'll handle this correctly, or handle the standard input/output yourself (though that's notoriously fraught with problems, I prefer something like commons-exec).

Danny Thomas
+5  A: 

You simply can't use pipes in a exec call. Pipes are a functionality of the shell and not of the operating system. So we have to call the shell executable and pass the command. Try this instead:

String[] command = new String[] {"cmd.exe", "/c", "start webRestarter.exe", ">>","webLog.log"};
Andreas_D
Thank you so much! This works:)
Kyle
A: 

Just thought I'd mention two things that might be handy for working with Processes.

  1. ProcessBuilder is a good way to obtain a Process (in code intended to run in a 1.5+ JRE).

  2. It is recommended to carefully read and implement all the recommendations of When Runtime.exec() won't.

Andrew Thompson