问题
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:
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"};
回答2:
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
回答3:
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).
回答4:
Just thought I'd mention two things that might be handy for working with Processes.
ProcessBuilder is a good way to obtain a Process (in code intended to run in a 1.5+ JRE).
It is recommended to carefully read and implement all the recommendations of When Runtime.exec() won't.
来源:https://stackoverflow.com/questions/3608944/adding-parameters-to-runtime-getruntime