? ? ? ? 有时候,我们需要java代码中调用cmd的命令,今天了解和测试了一下,代码如下:
Test.java
package demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class Test {
public static void main(String[] args) throws Exception {
//获取 环境对象
Runtime runtime = Runtime.getRuntime();
//设置需要执行的命令
String command = "ipconfig";
String temp = null;
StringBuilder sb = new StringBuilder();
//Process运行外部程序
Process process = runtime.exec(command);
//IO流读取返回结果
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(),Charset.forName("gbk") ));
while ((temp = bufferedReader.readLine()) != null) {
sb.append(temp + "\n");
}
//打印结果
System.out.println(sb.toString());
}
}
效果:
CMD执行ipconfig命令效果:
?
?
|