java ProcessBuilder 重定向输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5986324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ProcessBuilder redirecting output
提问by Chandra
I am trying to redirect output of a process started with the help of ProcessBuilder using following code
我正在尝试使用以下代码重定向在 ProcessBuilder 的帮助下启动的进程的输出
ProcessBuilder pb = new ProcessBuilder("/myScript >> /myLogFile 2>&1 <& - &");
Map<String, String> env = pb.environment();
env.clear();
env.put("var1", "val1");
env.put("var2", "val2");
pb.redirectErrorStream(true);
Process p = pb.start();
But it failed with exception
但它无一例外地失败了
Exception in thread "main" java.io.IOException: Cannot run program "/myScript >> /myLogFile 2>&1 <& - &": java.io.IOException: error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
线程“main”中的异常 java.io.IOException:无法运行程序“/myScript >> /myLogFile 2>&1 <& - &”:java.io.IOException:error=2,java.lang 中没有这样的文件或目录.ProcessBuilder.start(ProcessBuilder.java:460)
It works fine when I just pass "/myScript"
当我只通过“/myScript”时它工作正常
Script is perl, any suggestions/coments on why it is failing?
脚本是 perl,关于它为什么失败的任何建议/评论?
I tried passing all of them as seperate arguments like new ProcessBuilder("/myScript",">>","/myLogFile")
, it executes but it does not redirect to log file and also it does not take envVars.
我尝试将所有这些作为单独的参数传递,例如new ProcessBuilder("/myScript",">>","/myLogFile")
,它会执行但它不会重定向到日志文件,也不会使用 envVars。
回答by trashgod
Shell redirection operators are unknown to ProcessBuilder
. Put your command in a shell script and execute it, as shown here. Alternatively, use bash -c
, as shown here.
外壳重定向操作符是未知的ProcessBuilder
。把你的命令在shell脚本并执行它,如图所示这里。另外,使用bash -c
,如图所示这里。
回答by Hyman
As you specified, from Java7 you can keep using ProcessBuilder with the only executable file as parameter and redirect/intercept its output stream, using redirectInput()
redirectOutput()
and redirectError()
from ProcessBuilder
class.
正如您所指定的,从 Java7 开始,您可以继续使用 ProcessBuilder 并将唯一的可执行文件作为参数并重定向/拦截其输出流,使用redirectInput()
redirectOutput()
和redirectError()
来自ProcessBuilder
类。