Java JDK执行cmd命令的方法:
//在单独的进程中执行指定的字符串命令。 public Process exec(String command) throws IOException //在指定环境的独立进程中执行指定命令和变量 public Process exec(String command, String[] envp) throws IOException //在单独的进程中执行指定命令和变量 public Process exec(String cmdarray[]) throws IOException //在指定环境的独立进程中执行指定的命令和变量 public Process exec(String[] cmdarray, String[] envp) throws IOException //在有指定环境和工作目录的独立进程中执行指定的字符串命令 public Process exec(String command, String[] envp, File dir) throws IOException //在指定环境和工作目录的独立进程中执行指定的命令和变量 public Process exec(String[] cmdarray, String[] envp, File dir)
代码:
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) { // Java调用 dos命令 String cmd = "ping www.baidu.com"; try { Process process = Runtime.getRuntime().exec(cmd); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String content = br.readLine(); while (content != null) { System.out.println(content); content = br.readLine(); } //杀掉进程 process.destroy(); } catch (IOException e) { e.printStackTrace(); } } }