【Java】如何调用系统命令
如何通过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了,哈哈哈。
作者:Nick Huang 博客:http://www.cnblogs.com/nick-huang/
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~
本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。
如果本文对您有用,点赞或评论哦;如果您喜欢我的文章,请点击关注我哦~