使用Java实现Linux简易终端

it2026-08-06  9

核心工具类:

public final class CommandUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class); private static final Long THREAD_IDLE_MAX_SECONDS = 120L; /** * 系统换行符 */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(0, 2, THREAD_IDLE_MAX_SECONDS, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); /** * 执行Linux命令 * * @param command * @return */ public static RespDto execCommand(String command) { try { LOGGER.info("命令[" + command + "]开始执行!"); Process exec = Runtime.getRuntime().exec(command); Future<String> normalResult = EXECUTOR_SERVICE.submit(new PrintResult(exec.getInputStream())); Future<String> errorResult = EXECUTOR_SERVICE.submit(new PrintResult(exec.getErrorStream())); if (exec.waitFor() == 0) { String normal = normalResult.get(); LOGGER.info("命令[" + command + "]执行正常结束,执行结果[" + normal + "]"); return new RespDto.Builder().setData(normal).build(); } else { String error = errorResult.get(); LOGGER.error("命令[" + command + "]执行异常结束,执行结果[" + error + "]"); return new RespDto.Builder().setCode(RespCode.FAILURE.getCode()).setMessage("fail").setData(error) .build(); } } catch (Exception e) { LOGGER.error("命令[" + command + "]执行出错!", e); return new RespDto.Builder().setCode(RespCode.ERROR.getCode()).setMessage("error") .setData("命令[" + command + "]执行出错!").build(); } } private static class PrintResult implements Callable<String> { private InputStream is; public PrintResult(InputStream is) { this.is = is; } @Override public String call() throws Exception { StringBuffer sb = new StringBuffer(); BufferedReader br = null; try { InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { sb.append(line + LINE_SEPARATOR); } } finally { if (null != br) { br.close(); } } String result = sb.toString(); if (!StringUtils.isEmpty(result)) { result = result.substring(0, result.lastIndexOf(LINE_SEPARATOR)); } return result; } } }
最新回复(0)