使用ProcessBuilder运行shell脚本

时间:2017-08-08 14:17:31

标签: java linux process builder

我正在尝试使用Java和ProcessBuilder运行脚本。当我尝试运行时,收到以下消息:error = 2,没有这样的文件或目录。

我不知道我做错了什么,但这是我的代码(ps:我试图只执行没有参数的脚本,错误是一样的:

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
ProcessBuilder p = new ProcessBuilder(command);

    try {  

        // create a process builder to send a command and a argument
        Process p2 = p.start(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;

        log.info("Output of running " + command + " is: ");
        System.out.println("Output of running " + command + " is: ");
        while ((line = br.readLine()) != null) {
            log.info(line);
        }

    }  

3 个答案:

答案 0 :(得分:1)

尝试替换

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

有关详细信息,请参阅ProcessBuilder

  

ProcessBuilder(String ... command)

     

使用指定的操作系统构造流程构建器   程序和论点。

答案 1 :(得分:1)

除非你的script.sh名字中有逗号,否则就是错误:

String[] command = {"/teste/teste_back/script.sh" , argument1, argument};

答案 2 :(得分:0)

您可以使用ProcessBuilder定义方法。

public static Map execCommand(String... str) {
    Map<Integer, String> map = new HashMap<>();
    ProcessBuilder pb = new ProcessBuilder(str);
    pb.redirectErrorStream(true);
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = null;
    if (process != null) {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    }

    String line;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (process != null) {
            process.waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process != null) {
        map.put(0, String.valueOf(process.exitValue()));
    }

    try {
        map.put(1, stringBuilder.toString());
    } catch (StringIndexOutOfBoundsException e) {
        if (stringBuilder.toString().length() == 0) {
            return map;
        }
    }
    return map;
}

您可以调用该函数来执行shell命令或脚本

String cmds = "ifconfig";
String[] callCmd = {"/bin/bash", "-c", cmds};
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString());
System.out.println();
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());