怎么通过java去调用并执行shell脚本以及问题总结
2016-12-11 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
以下是我在公司项目中实际应用到的:
/** * 执行系统命令 * @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}; }}
/** * 执行系统命令 * @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}; }}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询