如何使用参数在Java中执行命令?
Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});
Run Code Online (Sandbox Code Playgroud)
不行吗?
String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);
Run Code Online (Sandbox Code Playgroud)
它是否也有效,因为它没有指定"m"参数.
我正在从Java程序执行shell脚本.我使用Runtime类实现了它.以下是我实施的代码
final StringBuilder sb = new StringBuilder("test.sh");
sb.append("/path to/my/text file");
final Process p = Runtime.getRuntime().exec(sb.toString());
Run Code Online (Sandbox Code Playgroud)
这里sb是字符串缓冲区对象,我在其中附加我的参数并在exec方法中使用它.但问题是我传递的参数"/ path to/my/text file"被认为是4个参数
/path
to
/my/text
file
Run Code Online (Sandbox Code Playgroud)
但是如果在shell中运行test.sh"/ path to/my/text file",它被视为单个参数.如何使用Java代码实现相同的功能,我需要将此路径与空格作为单个参数进行考虑.任何请你真的很感激.