简体   繁体   English

Java ProcessBuilder 传递参数

[英]Java ProcessBuilder Passing parameters

I have a shell script with one parameter, as follow:我有一个带有一个参数的 shell 脚本,如下所示:

test.sh测试文件

#!/bin/bash
echo "Shell Demo";
echo "Hello $0";

Now I want to execute this script using ProgressBuilder and pass parameters.现在我想使用 ProgressBuilder 执行这个脚本并传递参数。 The java code as follow: 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);
        }
    }

Output:输出:

Shell Demo
Hello ./test.sh

The output I want is:我想要的输出是:

Shell Demo
Hello Jack

You're going to want to remove that result.waitFor and also specify the executor to use, ie) bash (you can also use sh), other than that you're on the right path.您将要删除该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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM