通常 Java 执行 Windows 或者 Linux 的命令时,都是使用 Runtime.getRuntime.exec(command) 来执行的
public static void execCommand() { try { Runtime runtime = Runtime.getRuntime(); // 打开任务管理器,exec方法调用后返回 Process 进程对象 Process process = runtime.exec("cmd.exe /c taskmgr"); // 等待进程对象执行完成,并返回“退出值”,0 为正常,其他为异常 int exitValue = process.waitFor(); System.out.println("exitValue: " + exitValue); // 销毁process对象 process.destroy(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }}public static void execCommandAndGetOutput() { try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd.exe /c ipconfig"); // 输出结果,必须写在 waitFor 之前 String outStr = getStreamStr(process.getInputStream()); // 错误结果,必须写在 waitFor 之前 String errStr = getStreamStr(process.getErrorStream()); int exitValue = process.waitFor(); // 退出值 0 为正常,其他为异常 System.out.println("exitValue: " + exitValue); System.out.println("outStr: " + outStr); System.out.println("errStr: " + errStr); process.destroy(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }}public static String getStreamStr(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } br.close(); return sb.toString();}process对象可以通过操作数据流,对执行的命令进行参数输入、获取命令输出结果、获取错误结果
getInputStream() | 获取process进程的输出数据 |
|---|---|
getOutputStream() | 获取process进程的输入数据 |
getErrorStream() | 获取process进程的错误数据 |
值得注意的是:
getInputStream() 为什么是获取输出数据?getOutputStream()为什么是获取输入数据?这是因为 input 和 output 是__针对当前调用 process 的程序而言的__,即
要获取命令的输出结果,就是被执行命令的结果 输入到我们自己写的程序中,所以用getInputStream()
要往别的程序输入数据,就是我们程序要输出,所以此时用getOutputStream()