在Java中,你可以使用Runtime
类或ProcessBuilder
类来调用Linux脚本
方法1:使用Runtime类
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String scriptPath = "/path/to/your/script.sh";
Process process = Runtime.getRuntime().exec("bash " + scriptPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法2:使用ProcessBuilder类
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
try {
String scriptPath = "/path/to/your/script.sh";
ProcessBuilder processBuilder = new ProcessBuilder("bash", scriptPath);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这两个示例中,我们分别使用Runtime.getRuntime().exec()
和ProcessBuilder
类来执行Linux脚本。请注意,你需要将scriptPath
变量设置为你要执行的脚本的实际路径。这两个示例都会运行脚本并将输出打印到控制台。