java如何调用sh
调用Shell脚本的方法
在Java中调用Shell脚本可以通过Runtime类或ProcessBuilder类实现。这两种方法都能启动外部进程并执行Shell命令。
使用Runtime.exec()
Runtime.getRuntime().exec()是最简单的方法之一,适用于执行简单的Shell命令或脚本。
try {
Process process = Runtime.getRuntime().exec("/path/to/your/script.sh");
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
使用ProcessBuilder
ProcessBuilder提供了更灵活的控制,如设置工作目录和环境变量。
try {
ProcessBuilder pb = new ProcessBuilder("/path/to/your/script.sh");
pb.directory(new File("/working/directory"));
Process process = pb.start();
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
处理输入输出流
执行Shell脚本时,可能需要读取脚本的输出或错误信息。
Process process = Runtime.getRuntime().exec("/path/to/your/script.sh");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
传递参数
可以向Shell脚本传递参数,参数应作为数组传递给exec方法。

String[] cmd = {"/path/to/your/script.sh", "arg1", "arg2"};
Process process = Runtime.getRuntime().exec(cmd);
注意事项
确保脚本具有可执行权限,可以通过chmod +x script.sh命令赋予权限。对于复杂的脚本或长时间运行的进程,建议使用异步方式处理输出流以避免阻塞。






