【发布时间】:2012-10-11 06:07:40
【问题描述】:
我正在使用 Runtime.getRuntime().exec() 从 java 代码运行 shell 脚本。当我将参数作为字符串传递时,代码工作正常
Runtime.getRuntime().exec("sh test.sh")
由于我必须传递带有空格的路径的附加参数,所以我用字符串数组替换了字符串。
String[] cmd = {"sh test.sh", "/Path/to my/resource file"};
Runtime.getRuntime().exec(cmd)
我也试过
String[] cmd = {"sh test.sh"};
Runtime.getRuntime().exec(cmd)
但他们都没有工作。它抛出异常
java.io.IOException: Cannot run program "sh test.sh":
java.io.IOException: error=2, No such file or directory
为什么相同的脚本文件在作为字符串传递时有效,而与字符串数组一起使用时会引发异常。有没有人遇到过这个问题。请帮助我使用字符串数组作为 Runtime.exec() 的参数来完成这项工作。提前致谢。
【问题讨论】:
-
您应该使用上一个问题stackoverflow.com/questions/12812345/…中提到的
ProcessBuilder
标签: java shell runtime.exec