<!-- 第一个依赖,单独 --><dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version></dependency><!-- 第二个依赖,单独,目前看下来建议使用第二个--><dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-exec</artifactId> <version>1.12</version></dependency>
方法1
public static void exec() throws IOException, InterruptedException { CommandLine cmdLine = CommandLine.parse("sh aa.sh"); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(new File("/Users/chenshun/open/example-demo/springcloud-provider/src/main/resources/shell")); StringBuilder ss = new StringBuilder(); PumpStreamHandler streamHandler = new PumpStreamHandler(new LogOutputStream() { @Override protected void processLine(String line, int logLevel) { ss.append(line).append("\n\r"); System.out.println("SS logLevel:" + logLevel); } }); executor.setStreamHandler(streamHandler); executor.setExitValue(0); executor.setWatchdog(watchdog); System.out.println(cmdLine); final int execute = executor.execute(cmdLine); System.out.println("结束码:" + execute); System.out.println("正常的:" + ss.toString()); }
方法2
public static void exec2() throws Exception { final ProcessResult execute = new ProcessExecutor().command("/usr/local/bin/wkhtmltopdf", "https://zhuanlan.zhihu.com/p/425702746", "/Users/chenshun/Desktop/XrkrnMeAy.pdf") .readOutput(true) .execute(); final int exitValue = execute.getExitValue(); System.out.println("exit:" + exitValue); final ProcessOutput output = execute.getOutput(); for (String line : output.getLines()) { System.out.println(line); }}public static void exec3() throws Exception { final ProcessResult execute = new ProcessExecutor().command("sh", "aa.sh") .readOutput(true) .directory(new File("/Users/chenshun/open/example-demo/springcloud-provider/src/main/resources/shell")) .execute(); final int exitValue = execute.getExitValue(); System.out.println("exit:" + exitValue); final ProcessOutput output = execute.getOutput(); for (String line : output.getLines()) { System.out.println(line); }}