Runtime.getRuntime().exec怎么用
时间: 2023-12-15 20:48:42 浏览: 45
`Runtime.getRuntime().exec(command)` 方法可以用于在 Java 程序中执行外部命令。其中 `command` 参数是一个字符串数组,表示要执行的命令及其参数。
下面是一个简单的例子,演示如何使用 `Runtime.getRuntime().exec()` 方法来执行 `ls` 命令,并将输出打印到控制台:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecDemo {
public static void main(String[] args) {
try {
// 执行 ls 命令
Process p = Runtime.getRuntime().exec(new String[]{"ls", "-l"});
// 获取命令输出
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令执行完毕
int exitCode = p.waitFor();
System.out.println("Command exited with code " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上面的代码会在控制台输出 `ls -l` 命令的执行结果,并等待命令执行完毕后输出其退出码。需要注意的是,`Runtime.getRuntime().exec()` 方法返回的是一个 `Process` 对象,可以通过该对象获取命令的输入流、输出流和错误流等信息。