gpt4 book ai didi

Java ProcessBuilder 传递参数

转载 作者:行者123 更新时间:2023-12-01 18:39:28 25 4
gpt4 key购买 nike

我有一个带有一个参数的 shell 脚本,如下所示:

测试.sh

#!/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);
}
}

关于Java ProcessBuilder 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com