io.afu.utils.os.RunComand Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils Show documentation
Show all versions of utils Show documentation
RffanLAB Utils For Many Way use
package io.afu.utils.os;
import io.afu.common.exception.BaseException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* @author: RffanLAB.方露宇
*/
public class RunComand {
/**
* 执行系统命令
* @param cmd 系统命令(带参数)
* @return 执行返回结果
* @throws BaseException 抛错
*/
public static String runCMD(String[] cmd) throws BaseException {
Runtime runtime = Runtime.getRuntime();
Process p = null;
BufferedInputStream bufferedInputStream = null;
BufferedReader bufferedReader = null;
BufferedReader bufferedReaderErr = null;
String result = "";
try {
p = runtime.exec(cmd);
p.waitFor();
bufferedInputStream = new BufferedInputStream(p.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
bufferedReaderErr = new BufferedReader(new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8));
String lineStr;
StringBuilder stringBuilder = new StringBuilder();
while ((lineStr = bufferedReader.readLine()) != null){
System.out.println(lineStr);
stringBuilder.append(lineStr);
}
while ((lineStr = bufferedReaderErr.readLine()) != null){
stringBuilder.append(lineStr);
}
result = stringBuilder.toString();
}catch (Exception e){
throw new BaseException(e.getMessage());
}finally {
closeStream(bufferedReader);
closeStream(bufferedInputStream);
if (p != null){
p.destroy();
}
}
return result;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
// nothing
}
}
}
}