CmdUtils.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.fdkankan.modeldemo.utils;
  2. import lombok.extern.slf4j.Slf4j;
  3. /**
  4. * Created by Xiewj on 2021/1/4 0004 14:53
  5. */
  6. public class CmdUtils {
  7. /**
  8. * 调用 shell 脚本
  9. * @param command 命令
  10. */
  11. public static void callLineSh(String command) throws Exception {
  12. callLineSh(command, null);
  13. }
  14. /**
  15. * 直接通过 Java 调用命令
  16. * @param command 命令
  17. */
  18. public static void callLine(String command) throws Exception {
  19. callLine(command, null);
  20. }
  21. /**
  22. * 直接通过 Java 调用命令
  23. * @param command 命令
  24. * @param lineSize 日志输出行数,可以为 null
  25. */
  26. public static void callLine(String command, Integer lineSize) throws Exception {
  27. System.out.println("cmd: " + command);
  28. Process process = Runtime.getRuntime().exec(command);
  29. System.out.println("开始运行");
  30. StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR");
  31. errorGobbler.start();
  32. // 200 行打印一次日志
  33. StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize);
  34. outGobbler.start();
  35. process.waitFor();
  36. }
  37. /**
  38. * 调用 shell 脚本
  39. * @param command 命令
  40. * @param lineSize 日志输出行数,可以为 null
  41. */
  42. public static void callLineSh(String command, Integer lineSize) throws Exception {
  43. try {
  44. System.out.println("cmd: " + command);
  45. String[] cmd = new String[]{"/bin/sh", "-c", command};
  46. Process process = Runtime.getRuntime().exec(cmd);
  47. System.out.println("开始运行");
  48. StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR");
  49. errorGobbler.start();
  50. // 200 行打印一次日志
  51. StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize);
  52. outGobbler.start();
  53. process.waitFor();
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. }