import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CmdTest { public static void main(String[] args) { exeCmd("ping www.baidu.com"); } // Java调用 dos窗口命令 public static void exeCmd(String cmd) { try { Process process = Runtime.getRuntime().exec(cmd); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is,"GBK"); BufferedReader br = new BufferedReader(isr); String content = br.readLine(); while (content != null) { System.out.println(content); content = br.readLine(); } } catch ( IOException e) { e.printStackTrace(); } } }
不指定GBK的话会乱码,右键cmd窗口属性可以更改窗口的编码格式
说白了就是使用Process类的exec()方法将cmd的执行结果通过java的IO流输出到IDE的控
制台