以下是 Java 代码实现打开 Linux 终端并执行 Linux 命令的一个示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class LinuxCommandExecution {
public static void main(String[] args) {
String command = "ls -l"; // 要执行的 Linux 命令
try {
// 执行命令并获取输出流
Process process = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", command});
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 读取输出流
String line;
while ((line = output.readLine()) != null) {
System.out.println(line);
}
// 关闭输出流和进程
output.close();
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们使用 Java 的 Runtime.getRuntime().exec()
方法来执行 Linux 命令。该方法返回一个代表该进程的 Process
对象。我们可以从该对象获取该进程的输入流和输出流,以便读取命令的输出结果。最后,我们需要关闭输出流和销毁进程对象。注意,需要使用合适的参数调用 exec()
方法来确保使用 Bash Shell 执行命令。