java 运行时的 exec() 方法不重定向输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16238714/
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
Runtime's exec() method is not redirecting the output
提问by user2110167
Process p = Runtime.getRuntime().exec("sh somescript.sh &> out.txt");
I am running this command using Java. The script is running but it's not redirecting its stream to the file. Moreover, the file out.txt
is not getting created.
我正在使用 Java 运行此命令。脚本正在运行,但它没有将其流重定向到文件。此外,该文件out.txt
没有被创建。
This script runs fine if I run it on shell.
如果我在 shell 上运行它,这个脚本运行良好。
Any ideas?
有任何想法吗?
回答by johnchen902
You need to use ProcessBuilder
to redirect.
您需要使用ProcessBuilder
重定向。
ProcessBuilder builder = new ProcessBuilder("sh", "somescript.sh");
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("out.txt"));
Process p = builder.start(); // may throw IOException
回答by Peter Lawrey
When you run a command, there is no shell running and any shell commands or functions are not available. To use something like &>
you need a shell. You have one but you are not passing it to it. try instead.
当您运行命令时,没有外壳在运行,任何外壳命令或函数都不可用。要使用类似的东西,&>
您需要一个外壳。你有一个,但你没有把它传递给它。试试吧。
Runtime.getRuntime().exec(new String[] { "sh", "somescript.sh &> out.txt" });