Java 接口执行 Linux 命令:方法、示例和注意事项
在 Java 中,可以使用 'Runtime.getRuntime().exec(command)' 方法执行 Linux 命令。该方法返回一个 'Process' 对象,可以通过该对象获取命令的输出结果。
下面是一个使用接口执行 Linux 命令的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class LinuxCommandExecutor {
public static void main(String[] args) {
executeCommand("ls -l");
}
public static void executeCommand(String command) {
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,'executeCommand' 方法接受一个 Linux 命令作为参数,然后使用 'Runtime.getRuntime().exec(command)' 执行该命令。通过 'Process' 对象的 'getInputStream()' 方法获取命令的输出流,然后使用 'BufferedReader' 逐行读取输出结果并打印出来。
需要注意的是,使用 'Runtime.getRuntime().exec(command)' 执行命令时,命令参数需要按照正确的格式传递,比如使用空格分隔参数。另外,需要注意处理命令的输出流和错误流,以及处理命令执行过程中可能抛出的异常。
原文地址: https://www.cveoy.top/t/topic/o9H8 著作权归作者所有。请勿转载和采集!