Runtime's exec() method is not redirecting the output

我的梦境 提交于 2019-11-26 02:37:38

问题


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.

This script runs fine if I run it on shell.

Any ideas?


回答1:


You need to use ProcessBuilder to redirect.

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



回答2:


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


来源:https://stackoverflow.com/questions/16238714/runtimes-exec-method-is-not-redirecting-the-output

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