Runtime's exec() method is not redirec

2019-01-03 06:20发布

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?

2条回答
不美不萌又怎样
2楼-- · 2019-01-03 06:59

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" });
查看更多
不美不萌又怎样
3楼-- · 2019-01-03 07:00

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
查看更多
登录 后发表回答