Java可以通過Runtime類或ProcessBuilder類來調用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();
}
}
}
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腳本文件路徑。