向 Runtime.getRuntime() 添加参数?
void restartWeb() {
try {
String[] command = new String[] {"webRestarter.exe" , ">>","webLog.log"};
Runtime.getRuntime().exec(command);
} catch (java.io.IOException err) {
webServer.logError(err.getMessage());
}
}
为什么这不起作用?我该如何修复它,使其按照我想要的方式工作?
-- 使用参数执行 webRestarter.exe >>webLog.log
所以它会输出如下内容:
webRestarter.exe>>webLog.log
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
参数直接传递给 webRestarter.exe 命令。您不能使用参数将标准输出重定向到文件,因为这通常是由命令行解释器完成的。
但是,exec() 方法返回一个 Process 对象,您可以使用它来检索标准输出并将其写入文件。
来源:
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
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
如果我没记错的话,管道、重定向等都是 shell 的功能。在这种情况下,这些只是论点。您可以像使用 cmd.exe 一样简单地处理这个问题,并将 /c 开关作为命令的一部分,我相信它会正确处理这个问题,或者自己处理标准输入/输出(尽管这众所周知充满了问题,但我更喜欢一些东西)像commons-exec)。
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).
只是想我会提到两件事可能对处理流程很方便。
ProcessBuilder
是获取进程的好方法(在
旨在在 1.5+ JRE 中运行的代码)。
建议谨慎
阅读并实施全部
何时的建议
Runtime.exec() 不会。
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.
您根本无法在
exec
调用中使用管道。管道是 shell 的一项功能,而不是操作系统的一项功能。所以我们必须调用 shell 可执行文件并传递命令。试试这个: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: