开发者

Adding parameters to Runtime.getRuntime()?

开发者 https://www.devze.com 2023-01-13 16:43 出处:网络
void restartWeb() { try { String[] command = new String[] {\"webRest开发者_开发知识库arter.exe\" , \">>\",\"webLog.log\"};
void restartWeb() {
        try {
            String[] command = new String[] {"webRest开发者_开发知识库arter.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


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"};


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


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消