How can Java call a shell script?
In Java, you can use the ProcessBuilder class to execute shell scripts. Here is an example code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellScriptExample {
public static void main(String[] args) {
try {
// 创建ProcessBuilder对象并指定要执行的命令
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "/path/to/script.sh");
// 设置工作目录(可选)
processBuilder.directory(new File("/path/to/directory"));
// 启动命令并获取进程对象
Process process = processBuilder.start();
// 读取命令的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令执行完毕
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("命令执行成功");
} else {
System.out.println("命令执行失败");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
In the code above, we use the ProcessBuilder class to set the command to be executed and the working directory. Then, we use the start() method to launch the command and get the process object. We can retrieve the output of the command by using the getInputStream() method to read the output stream.
Finally, we use the waitFor() method to wait for the command to be executed and retrieve the exit code of the command. By checking the value of the exit code, we can determine whether the command was executed successfully.
Please note that the command paths and working directory in the examples above should be modified according to your actual situation.