You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.3 KiB
75 lines
2.3 KiB
package com.insigma.utils;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.util.StringUtils;
|
|
|
|
import java.io.*;
|
|
|
|
/**
|
|
* CommandImpUtil Windows 下执行命令 <br/>
|
|
* 【注意】 目录使用的 >>> 下划线 <<<
|
|
*
|
|
* @author admin
|
|
*/
|
|
@Slf4j
|
|
@SuppressWarnings("DuplicatedCode")
|
|
public class WinCommandUtil implements Runnable {
|
|
private String command;
|
|
|
|
private final String CMD = "cmd";
|
|
private final String EXE = "cmd /c ";
|
|
public WinCommandUtil(String command) {
|
|
if(StringUtils.startsWithIgnoreCase(command, CMD)){
|
|
this.command = command;
|
|
}else{
|
|
this.command = EXE + command;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
Process process;
|
|
int exitVal = 0;
|
|
try {
|
|
log.debug("准备执行命令:{}",command);
|
|
process = Runtime.getRuntime().exec(command);
|
|
// Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
|
|
//针对这种情况,我们只需要将子进程的stream重定向出来即可。
|
|
new RunCmdStreamThread(process.getInputStream(), "INFO").start();
|
|
new RunCmdStreamThread(process.getErrorStream(), "ERR").start();
|
|
|
|
exitVal = process.waitFor();
|
|
} catch (IOException | InterruptedException e) {
|
|
log.error("执行命令发生异常:{}", e.getMessage());
|
|
}
|
|
|
|
if (exitVal != 0) {
|
|
throw new RuntimeException("cmd任务执行失败");
|
|
}
|
|
}
|
|
|
|
static class RunCmdStreamThread extends Thread {
|
|
InputStream is;
|
|
String printType;
|
|
|
|
RunCmdStreamThread(InputStream is, String printType) {
|
|
this.is = is;
|
|
this.printType = printType;
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
try {
|
|
InputStreamReader isr = new InputStreamReader(is);
|
|
BufferedReader br = new BufferedReader(isr);
|
|
String line;
|
|
while ((line = br.readLine()) != null) {
|
|
log.debug("输出:{}>{}", printType, line);
|
|
}
|
|
|
|
} catch (IOException ioe) {
|
|
ioe.printStackTrace();
|
|
}
|
|
}
|
|
}
|
|
}
|