org.kaizen4j.common.util.ProcessUtils Maven / Gradle / Ivy
package org.kaizen4j.common.util;
import com.google.common.base.Throwables;
import java.io.*;
import static java.util.Objects.nonNull;
/**
* 系统命令执行工具类
*
* @author John
*/
public final class ProcessUtils {
/**
* 执行命令
*
* @param command 命令字符串
* @param charset 字符集
* @return String 执行结果
*
* @throws IOException
*/
public static String execute(String command, String charset) {
return execute(new String[] {command}, charset);
}
/**
* 执行命令
*
* @param command 命令字符串数组
* @param charset 字符集
* @return String 执行结果
*
* @throws IOException
*/
public static String execute(String[] command, String charset) {
Writer writer = new StringWriter();
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(), charset));
String line;
while (nonNull(line = stdInput.readLine())) {
writer.write(line);
}
while (nonNull(line = stdError.readLine())) {
writer.write(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return writer.toString();
}
}