工作中需要用java調用外部命令(shell腳本,啟動服務等),之前使用Runtime.getRuntime().exec調用外部程序,Runtime.getRuntime().exec是java原生態的命令,而Apache commons-exec封裝一些常用的方法用來執行外部命令。例如我們想得到當前windows目錄下的文件信息,在cmd命令行下的命令是dir。具體以代碼示例展示2個方法實現。
第一種Runtime.getRuntime().exec
String pl_cmd = "cmd.exe /c dir"; Process p_pl = Runtime.getRuntime().exec(pl_cmd); BufferedReader br_pl = new BufferedReader(new InputStreamReader( p_pl.getInputStream())); String stdout = br_pl.readLine(); while (stdout != null) { System.out.println(stdout); stdout = br_pl.readLine(); }
第二種Apache commons-exec
ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); CommandLine cl = CommandLine.parse("cmd.exe /c dir"); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(psh); exec.execute(cl); System.out.println(stdout.toString());
代碼參考github
其他工程參考鏈接
https://github.com/wucao/JDeploy