如何通过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..."); } } }