Java Shell命令调用及交互算法封装 | S学习笔记

关注
Java Shell命令调用及交互算法封装 | S学习笔记www.shan-machinery.com简介

Java调用Shell命令运行子进程的方式如下代码:123456ProcessBuilder processBuilder = new ProcessBuilder("pwd");Process process = processBuilder.start();if (process.waitFor(timeout, TimeUnit.MILLISECONDS)) {status = process.exitValue();System.out.println(status);}

现在需要在子进程运行过程中,实时收集子进程输出流的行输出,因此需要设计算法实现该功能。

设计

采用监听模式,调用子进程执行Shell命令同时注册监听器子进程行输出将以实时调用监听器对象传参的方式传递给监听器。

原始程序流程图:image

核心代码片段12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758public static int execute(String command, String directory, Long timeout, final Communicator... communicators) throws CommandTimeoutException {final ProcessBuilder processBuilder = new ProcessBuilder(command);if (directory != null) {File workDir = new File(directory);if (workDir.exists() && workDir.isDirectory()) {processBuilder.directory(workDir);}}processBuilder.redirectErrorStream(true);int status = -1;try {final Process process = processBuilder.start();if (communicators != null && communicators.length > 0) {communicatorExecutor.submit(() -> {BufferedReader reader = null;try {InputStream inputStream = process.getInputStream();if (inputStream == null) {return;}reader = new BufferedReader(new InputStreamReader(inputStream));String line;while ((line = reader.readLine()) != null) {for (Communicator communicator : communicators) {communicator.onMessage(line, process);}}} catch (Exception e) {logger.warn(e.getMessage(), e);} finally {if (reader != null) {try {reader.close();} catch (Exception e) {logger.warn(e.getMessage(), e);}}}});}if (timeout == null || timeoutSystem.out.println(message));System.out.println("exitValue: " + exitValue);} catch (ShellExecutor.CommandTimeoutException e) {System.out.println(e.getMessage());}}

Shell脚本 test.sh 如下:12345678910111213#!/bin/bashsource /etc/profilei=0while((${i} < 20))doecho "Printout success, index: ${i}"let "i++"sleep 2doneexit 0

结果输出123456789101112131415161718192021Printout success, index: 0Printout success, index: 1Printout success, index: 2Printout success, index: 3Printout success, index: 4Printout success, index: 5Printout success, index: 6Printout success, index: 7Printout success, index: 8Printout success, index: 9Printout success, index: 10Printout success, index: 11Printout success, index: 12Printout success, index: 13Printout success, index: 14Printout success, index: 15Printout success, index: 16Printout success, index: 17Printout success, index: 18Printout success, index: 19exitValue: 0

代码仓库

https://github.com/johnsonmoon/ShellExecutor.git

https://www.shan-machinery.com