Adding parameters to Runtime.getRuntime()?

蹲街弑〆低调 提交于 2020-02-06 05:49:31

问题


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.

  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.



来源:https://stackoverflow.com/questions/3608944/adding-parameters-to-runtime-getruntime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!