调用系统的DOS下令方法执行需要的命令
调用系统的DOS命令方法执行需要的命令
package com.huaweisymantec.core.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 命令行命令执行工具类 * * @author s00108907 * */ public final class CommandUtils { private static final Logger LOG = LoggerFactory.getLogger(CommandUtils.class); /** * 调用系统的DOS命令方法执行需要的命令 * * @param command 要执行的命令 * @return 执行结果 * @throws IOException */ public static String exec(String command) throws IOException { return exec(null, command); } /** * 调用系统的DOS命令方法执行需要的命令 * * @param directory 此进程的工作目录 * @param command 要执行的命令 * @return 执行结果 * @throws IOException */ public static String exec(String directory, String command) throws IOException { InputStream in = null; Reader reader = null; BufferedReader br = null; try { ProcessBuilder pb; if (System.getProperty("os.name").indexOf("Windows") == -1) { pb = new ProcessBuilder("/bin/sh", "-c", command); } else { pb = new ProcessBuilder("cmd", "/c", command); } if (StringUtils.isNotBlank(directory)) { pb.directory(new File(directory)); } // merge the error output with the standard output pb.redirectErrorStream(true); LOG.debug("Now exceuting:{}", command); Process p = pb.start(); in = p.getInputStream(); reader = new InputStreamReader(in, "gb2312"); br = new BufferedReader(reader); StringBuffer lines = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { lines.append(line).append("\r\n"); } LOG.debug("Exceuting result:{}", lines.toString()); return lines.toString(); } finally { if (reader != null) { reader.close(); } if (br != null) { br.close(); } if (in != null) { in.close(); } } } }