[英]Java ProcessBuilder Passing parameters
我有一个带有一个参数的 shell 脚本,如下所示:
测试文件
#!/bin/bash
echo "Shell Demo";
echo "Hello $0";
现在我想使用 ProgressBuilder 执行这个脚本并传递参数。 java代码如下:
public void testShell() throws Exception {
String shPath = "./test.sh";
// want to pass a value "Jack" to shell script
ProcessBuilder builder = new ProcessBuilder(shPath, "Jack");
Process result = builder.start();
result.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream()));
String output;
while ((output = stdInput.readLine()) != null) {
System.out.println(output);
}
}
输出:
Shell Demo
Hello ./test.sh
我想要的输出是:
Shell Demo
Hello Jack
您将要删除该result.waitFor
并指定要使用的执行程序,即)bash(您也可以使用 sh),除了您在正确的路径上。
public String[] createExecutionString(String process, String...params) {
final List<String> executor = new ArrayList<>();
executor.add("bash"); /* cmd on windows */
executor.add("-c"); /* /c on windows */
executor.add(process);
for (String param : params) {
executor.add(param);
}
return executor.toArray(new String[0]);
}
public void testShell() throws Exception {
String shPath = "./test.sh";
// want to pass a value "Jack" to shell script
ProcessBuilder builder = new ProcessBuilder(createExecutionString(shPath, "Jack"));
Process result = builder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream()));
String output;
while ((output = stdInput.readLine()) != null) {
System.out.println(output);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.