package com.fdkankan.modeldemo.utils; import lombok.extern.slf4j.Slf4j; /** * Created by Xiewj on 2021/1/4 0004 14:53 */ public class CmdUtils { /** * 调用 shell 脚本 * @param command 命令 */ public static void callLineSh(String command) throws Exception { callLineSh(command, null); } /** * 直接通过 Java 调用命令 * @param command 命令 */ public static void callLine(String command) throws Exception { callLine(command, null); } /** * 直接通过 Java 调用命令 * @param command 命令 * @param lineSize 日志输出行数,可以为 null */ public static void callLine(String command, Integer lineSize) throws Exception { System.out.println("cmd: " + command); Process process = Runtime.getRuntime().exec(command); System.out.println("开始运行"); StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR"); errorGobbler.start(); // 200 行打印一次日志 StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize); outGobbler.start(); process.waitFor(); } /** * 调用 shell 脚本 * @param command 命令 * @param lineSize 日志输出行数,可以为 null */ public static void callLineSh(String command, Integer lineSize) throws Exception { try { System.out.println("cmd: " + command); String[] cmd = new String[]{"/bin/sh", "-c", command}; Process process = Runtime.getRuntime().exec(cmd); System.out.println("开始运行"); StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR"); errorGobbler.start(); // 200 行打印一次日志 StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize); outGobbler.start(); process.waitFor(); } catch (Exception e) { e.printStackTrace(); } } }