use*_*167 17 java shell process runtime.exec
Process p = Runtime.getRuntime().exec("sh somescript.sh &> out.txt");
Run Code Online (Sandbox Code Playgroud)
我正在使用Java运行此命令.该脚本正在运行,但它没有将其流重定向到该文件.而且,文件out.txt没有被创建.
如果我在shell上运行它,这个脚本运行正常.
有任何想法吗?
joh*_*902 35
您需要使用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
Run Code Online (Sandbox Code Playgroud)
运行命令时,没有shell运行,并且任何shell命令或函数都不可用.使用像&>你需要的东西.你有一个,但你没有把它传递给它.试着改为.
Runtime.getRuntime().exec(new String[] { "sh", "somescript.sh &> out.txt" });
Run Code Online (Sandbox Code Playgroud)