package org.kanpiaoxue.util; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * <pre> * StreamGobbler.java * @author kanpiaoxue<br> * @version 1.0 * Create Time 2014年9月11日 上午10:54:38<br> * Description : 外部数据流消费器 * </pre> */ public final class StreamGobbler extends Thread { private static final Logger LOGGER = LoggerFactory .getLogger(StreamGobbler.class); private static final String ERROR_MSG = "error"; private final InputStream is; /** * <pre> * 是否需要打印错误log * </pre> */ private final boolean printErrorLog; /** * <pre> * @param is 输入流 * @param type 类型 * </pre> */ public StreamGobbler(InputStream is, String type) { super(); Preconditions.checkNotNull(is, "InputStream is null."); Preconditions.checkArgument(!Strings.isNullOrEmpty(type), "type is null or empty!"); this.is = is; this.printErrorLog = type.trim() .equalsIgnoreCase(ERROR_MSG); } /* * (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { for (String line = reader.readLine(); line != null; line = reader .readLine()) { // 根据标识位打印出不同的log格式 if (printErrorLog) { LOGGER.debug("{}>{}", ERROR_MSG, line); } else { LOGGER.debug(line); } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); } } }
举例如下:下面的代码不完整
String msg = String.format("execute cmd:%s", cmd); LOGGER.info(msg); Stopwatch w = Stopwatch.createStarted(); Process process = Runtime.getRuntime().exec(cmd); // 消费掉IO流,防止程序被阻塞卡死 new StreamGobbler(process.getInputStream(), "normal").start(); new StreamGobbler(process.getErrorStream(), "error").start(); int exitCode = process.waitFor(); boolean flag = (0 == exitCode); LOGGER.info("{}. exitCode : {}, -->{}! It consumes {}", msg, exitCode, (flag ? "SUCCESS" : "FAILURE"), w.toString());