怎么通过java去调用并执行shell脚本以及问题总结

2024-12-20 04:07:53
推荐回答(1个)
回答1:

以下是我在公司项目中实际应用到的:
/** * 执行系统命令 * @time 2016/10/17$ 17:05$ */public final class SystemCommandExecutor { protected static Logger logger = LoggerFactory.getLogger(ShareDiskFileUtils.class); public static final boolean isWindow; public static final boolean isLinux; static { String osname = System.getProperty("os.name").toLowerCase(); isWindow = osname.contains("win"); isLinux = osname.contains("linux"); logger.info("系统环境: " + (isLinux ? "Linux" : "Window")); } /** * 执行命令 */ public static Process executeCommand(String command) throws IOException, InterruptedException { logger.info("执行系统命令: " + command); Process process = Runtime.getRuntime().exec(getCmdArray(command)); new StreamPrinter(process.getInputStream(), logger).start(); new StreamPrinter(process.getErrorStream(), logger).start(); process.waitFor(); return process; } /** * 这个非常重要, 如果你直接执行command,会出现一些问题,如果参数中包含一些空格,", ' 之类的特殊字符,将会执行失败, */ private static String[] getCmdArray(String command) { if (isWindow) { return new String[]{"cmd", "/c", command}; } if (isLinux) { return new String[]{"/bin/sh", "-c", command}; } return new String[]{"cmd", "/c", command}; }}