• 创建一个字符串数组来存储 shell 脚本及其参数;
  • 使用 ProcessBuilder 类创建一个新的进程,并将字符串数组作为参数传递给其 start() 方法;
  • 使用 Process 对象的 getInputStream() 和 getErrorStream() 方法读取 shell 脚本的输出。
  • 代码实现如下:

    String[] command = {"/bin/sh", "-c", "./your_script.sh arg1 arg2"};
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    int exitCode = process.waitFor();
    System.out.println("Exit code: " + exitCode);
    
  •