温馨提示×

java怎么调用shell脚本

小亿
103
2024-01-22 11:02:20
栏目: 编程语言

Java可以通过Runtime类或ProcessBuilder类来调用Shell脚本。

  1. 使用Runtime类调用Shell脚本:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunShellScript {
    public static void main(String[] args) {
        try {
            // 调用Shell脚本的命令
            String command = "sh /path/to/script.sh";

            // 执行Shell脚本
            Process process = Runtime.getRuntime().exec(command);

            // 获取Shell脚本的输出结果
            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("Shell脚本执行完成,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用ProcessBuilder类调用Shell脚本:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class RunShellScript {
    public static void main(String[] args) {
        try {
            // 调用Shell脚本的命令
            List<String> command = List.of("sh", "/path/to/script.sh");

            // 创建ProcessBuilder对象,并设置命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);

            // 设置工作目录
            processBuilder.directory(null); // 设置为null表示使用当前工作目录

            // 执行Shell脚本
            Process process = processBuilder.start();

            // 获取Shell脚本的输出结果
            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("Shell脚本执行完成,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

注意:在调用Shell脚本时需要根据实际情况替换/path/to/script.sh为实际的Shell脚本文件路径。

0