Java运行cmd终端命令
时间: 2023-09-05 08:13:23 浏览: 107
cmd命令指令学习资源
Java可以通过Runtime类或ProcessBuilder类来执行cmd终端命令。
使用Runtime类:
```java
Runtime runtime = Runtime.getRuntime();
String cmd = "dir"; //要执行的命令
Process process = runtime.exec(cmd); //执行命令
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); //输出命令执行结果
}
```
使用ProcessBuilder类:
```java
ProcessBuilder builder = new ProcessBuilder();
builder.command("cmd.exe", "/c", "dir"); //要执行的命令
Process process = builder.start(); //执行命令
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); //输出命令执行结果
}
```
注意,在执行命令时需要注意命令的参数和输出结果的编码格式。
阅读全文