package org.springrain.frame.util;@b@@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@import java.io.BufferedReader;@b@import java.io.InputStreamReader;@b@import java.util.ArrayList;@b@import java.util.List;@b@@b@/**@b@ * 执行命令行的工具类,需要提前设定执行权限@b@ *@b@ * @author caomei@b@ */@b@public class CmdUtils {@b@ private static final Logger logger = LoggerFactory.getLogger(CmdUtils.class);@b@@b@ private CmdUtils() {@b@ throw new IllegalAccessError("工具类不能实例化");@b@ }@b@@b@ /**@b@ * 执行命令行@b@ *@b@ * @param commandStr@b@ * @return@b@ */@b@ public static List<String> execCmd(String commandStr) {@b@ final String os = System.getProperty("os.name").toLowerCase();@b@ if (os.contains("windows")) {@b@ return execWindowsCmd(commandStr);@b@ } else if (os.contains("linux")) {@b@ return execLinuxCmd(commandStr);@b@ } else {@b@ return null;@b@ }@b@ }@b@@b@ /**@b@ * 执行命令行@b@ *@b@ * @param pb@b@ * @return@b@ */@b@ public static List<String> execCmd(ProcessBuilder pb) {@b@@b@ BufferedReader br = null;@b@ try {@b@@b@ Process p = pb.start();@b@ br = new BufferedReader(new InputStreamReader(p.getInputStream()));@b@ String line = null;@b@ List<String> list = new ArrayList<>();@b@ while ((line = br.readLine()) != null) {@b@ list.add(line);@b@ }@b@@b@ return list;@b@@b@ } catch (Exception e) {@b@ logger.error(e.getMessage(), e);@b@ return null;@b@ } finally {@b@ if (br != null) {@b@ try {@b@ br.close();@b@ } catch (Exception e) {@b@ logger.error(e.getMessage(), e);@b@ }@b@ }@b@ }@b@ }@b@@b@ /**@b@ * 执行Windows命令@b@ *@b@ * @param commandStr@b@ * @return@b@ */@b@ private static List<String> execWindowsCmd(String commandStr) {@b@ List<String> cmds = new ArrayList<>();@b@ cmds.add("cmd.exe");@b@ cmds.add("/c");@b@ cmds.add(commandStr);@b@ ProcessBuilder pb = new ProcessBuilder(cmds);@b@ //正常信息和错误信息合并输出,有些情况信息会在错误信息里,例如ffmpeg@b@ pb.redirectErrorStream(true);@b@ return execCmd(pb);@b@ }@b@@b@ /**@b@ * 执行Linux命令@b@ *@b@ * @param commandStr@b@ * @return@b@ */@b@ private static List<String> execLinuxCmd(String commandStr) {@b@ List<String> cmds = new ArrayList<>();@b@ cmds.add("sh");@b@ cmds.add("-c");@b@ cmds.add(commandStr);@b@ ProcessBuilder pb = new ProcessBuilder(cmds);@b@ //正常信息和错误信息合并输出,有些情况信息会在错误信息里,例如ffmpeg@b@ pb.redirectErrorStream(true);@b@ return execCmd(pb);@b@ }@b@@b@ /**@b@ * public static void main(String[] args) { StringBuilder execCmd =@b@ * execCmd("ipconfig /all"); System.out.println(execCmd.toString()); }@b@ */@b@}