如何通过Java调用系统命令,如ping 127.0.0.1、java -version等?
> 简单的例子
package com.nicchagil.callpython.No001无参数调用; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class HowToCallSystemCommand { public static void main(String[] args) { BufferedReader in = null; try { /* 调用、输出 */ Process process = Runtime.getRuntime().exec("ping 127.0.0.1"); in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } /* 判断是否正常 */ int waitFor = process.waitFor(); System.out.println("waitFor -> " + waitFor); if (process.waitFor() == 0) { System.out.println("Normal termination."); } else { System.out.println("Abnormal termination."); } } catch (Exception e) { // TODO e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // TODO e.printStackTrace(); } } System.out.println("Done..."); } } }
执行后,发现对于“ping 127.0.0.1”能完整的打印出日志,而对于“java -version”却无日志输出,原因在于它们输出的级别不同。
于是,作了下简单修改。
package com.nicchagil.callpython.No001无参数调用; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class HowToCallSystemCommand { public static void main(String[] args) { BufferedReader inputBufferedReader = null; BufferedReader errorBufferedReader = null; try { /* 调用、输出 */ Process process = Runtime.getRuntime().exec("java -version"); inputBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line = null; System.out.println("Input Stream -> "); while ((line = inputBufferedReader.readLine()) != null) { System.out.println(line); } System.out.println("Error Stream -> "); while ((line = errorBufferedReader.readLine()) != null) { System.out.println(line); } /* 判断是否正常 */ int waitFor = process.waitFor(); System.out.println("waitFor -> " + waitFor); if (process.waitFor() == 0) { System.out.println("Normal termination."); } else { System.out.println("Abnormal termination."); } } catch (Exception e) { // TODO e.printStackTrace(); } finally { if (inputBufferedReader != null) { try { inputBufferedReader.close(); } catch (IOException e) { // TODO e.printStackTrace(); } } System.out.println("Done..."); } } }
分别执行两个命令,查询日志,发现OK了,哈哈哈。