1. <!-- 第一个依赖,单独 -->
  2. <dependency>
  3. <groupId>org.apache.commons</groupId>
  4. <artifactId>commons-exec</artifactId>
  5. <version>1.3</version>
  6. </dependency>
  7. <!-- 第二个依赖,单独,目前看下来建议使用第二个-->
  8. <dependency>
  9. <groupId>org.zeroturnaround</groupId>
  10. <artifactId>zt-exec</artifactId>
  11. <version>1.12</version>
  12. </dependency>

方法1

  1. public static void exec() throws IOException, InterruptedException {
  2. CommandLine cmdLine = CommandLine.parse("sh aa.sh");
  3. ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
  4. DefaultExecutor executor = new DefaultExecutor();
  5. executor.setWorkingDirectory(new File("/Users/chenshun/open/example-demo/springcloud-provider/src/main/resources/shell"));
  6. StringBuilder ss = new StringBuilder();
  7. PumpStreamHandler streamHandler = new PumpStreamHandler(new LogOutputStream() {
  8. @Override
  9. protected void processLine(String line, int logLevel) {
  10. ss.append(line).append("\n\r");
  11. System.out.println("SS logLevel:" + logLevel);
  12. }
  13. });
  14. executor.setStreamHandler(streamHandler);
  15. executor.setExitValue(0);
  16. executor.setWatchdog(watchdog);
  17. System.out.println(cmdLine);
  18. final int execute = executor.execute(cmdLine);
  19. System.out.println("结束码:" + execute);
  20. System.out.println("正常的:" + ss.toString());
  21. }

方法2

  1. public static void exec2() throws Exception {
  2. final ProcessResult execute = new ProcessExecutor().command("/usr/local/bin/wkhtmltopdf", "https://zhuanlan.zhihu.com/p/425702746", "/Users/chenshun/Desktop/XrkrnMeAy.pdf")
  3. .readOutput(true)
  4. .execute();
  5. final int exitValue = execute.getExitValue();
  6. System.out.println("exit:" + exitValue);
  7. final ProcessOutput output = execute.getOutput();
  8. for (String line : output.getLines()) {
  9. System.out.println(line);
  10. }
  11. }
  12. public static void exec3() throws Exception {
  13. final ProcessResult execute = new ProcessExecutor().command("sh", "aa.sh")
  14. .readOutput(true)
  15. .directory(new File("/Users/chenshun/open/example-demo/springcloud-provider/src/main/resources/shell"))
  16. .execute();
  17. final int exitValue = execute.getExitValue();
  18. System.out.println("exit:" + exitValue);
  19. final ProcessOutput output = execute.getOutput();
  20. for (String line : output.getLines()) {
  21. System.out.println(line);
  22. }
  23. }