主要针对win下java调用命令行操作
基于java17开发,请注意jdk版本
核心功能:
执行基础的命令,建议批量命令写成bat,然后直调用。
public static ExecResult exec(String cmd) {
//默认30分钟没有输出强行关闭
return exec(cmd, 30 * 60);
}
public static ExecResult exec(String cmd, int timeout) {
ExecResult execResult = new ExecResult();
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
if (!isWindows) {
execResult.setCode(1);
return execResult;
}
try {
Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});
DelayTask processDelayTaskTask = new DelayTask<>(process.pid(), timeout * 1000L, process);
TASK_KILL_QUEUE.put(processDelayTaskTask);
//执行中的普通输出
CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> execResult.setResult(getExecResultAndRefresh(process.inputReader(), process, timeout)));
//执行中的错误输出
CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> getExecResultAndRefresh(process.errorReader(), process, timeout));
//阻塞等待结果
execResult.setCode(process.waitFor());
TASK_KILL_QUEUE.removeById(processDelayTaskTask.getId());
return execResult;
} catch (Exception e) {
e.printStackTrace();
execResult.setCode(1);
}
return execResult;
}
拓展功能:
有些命令行执行复杂牵扯到第三方调用,可能会卡住(无限期等待),因此需要配置执行超时时间,执行过程中,没有任何输出完全不响应时需要杀掉脚本进程
完整代码:
public class ExecUtils {
private static final AnalogDelayQueue, Long> TASK_KILL_QUEUE = new AnalogDelayQueue<>();
private static final ThreadPoolExecutor CALLER_RUNS_POLICY_THREAD_POOL = new ThreadPoolExecutor(10, 50, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy());
private ExecUtils() {
CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
DelayTask delayMessage = TASK_KILL_QUEUE.take();
Process process = delayMessage.getData();
process.destroy();
log.error("触发强制关闭!!!{}", process);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public static ExecResult exec(String cmd) {
//默认30分钟没有输出强行关闭
return exec(cmd, 30 * 60);
}
public static ExecResult exec(String cmd, int timeout) {
ExecResult execResult = new ExecResult();
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
if (!isWindows) {
execResult.setCode(1);
return execResult;
}
try {
Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});
DelayTask processDelayTaskTask = new DelayTask<>(process.pid(), timeout * 1000L, process);
TASK_KILL_QUEUE.put(processDelayTaskTask);
//执行中的普通输出
CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> execResult.setResult(getExecResultAndRefresh(process.inputReader(), process, timeout)));
//执行中的错误输出
CALLER_RUNS_POLICY_THREAD_POOL.execute(() -> getExecResultAndRefresh(process.errorReader(), process, timeout));
//阻塞等待结果
execResult.setCode(process.waitFor());
TASK_KILL_QUEUE.removeById(processDelayTaskTask.getId());
return execResult;
} catch (Exception e) {
e.printStackTrace();
execResult.setCode(1);
}
return execResult;
}
private static String getExecResultAndRefresh(BufferedReader bufferedReader, Process process, int timeout) {
try (bufferedReader) {
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
TASK_KILL_QUEUE.rePut(new DelayTask<>(process.pid(), timeout * 1000L, process));
stringBuilder.append(line).append("n");
log.info(line);
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public interface AnalogDelayedextends Delayed { T getId(); }
public class AnalogDelayQueue, T> extends DelayQueue { public void rePut(E task) { synchronized (this) { //如果有对应的delayTask,则将delayTask取出来并从消息队列中移除 this.removeById(task.getId()); //放到延时队列 this.put(task); } } public void removeById(T t) { super.removeIf(o -> o.getId().equals(t)); } }
@Data
@NoArgsConstructor
public class DelayTask implements AnalogDelayed {
private I taskId;
private long time;
private V data;
public DelayTask(I taskId, long millisecond, V data) {
this.taskId = taskId;
this.data = data;
this.time = millisecond + System.currentTimeMillis();
}
@Override
public I getId() {
return this.taskId;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS) > 0 ? 1 : -1;
}
}



