时间:2023-01-26 09:46:28 | 栏目:JAVA代码 | 点击:次
1. java 执行shell
java 通过 Runtime.getRuntime().exec() 方法执行 shell 的命令或 脚本,exec()方法的参数可以是脚本的路径也可以是直接的 shell命令
代码如下(此代码是存在问题的。完整代码请看2):
/** * 执行shell * @param execCmd 使用命令 或 脚本标志位 * @param para 传入参数 */ private static void execShell(boolean execCmd, String... para) { StringBuffer paras = new StringBuffer(); Arrays.stream(para).forEach(x -> paras.append(x).append(" ")); try { String cmd = "", shpath = ""; if (execCmd) { // 命令模式 shpath = "echo"; } else { //脚本路径 shpath = "/Users/yangyibo/Desktop/callShell.sh"; } cmd = shpath + " " + paras.toString(); Process ps = Runtime.getRuntime().exec(cmd); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String result = sb.toString(); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } }
2. 遇到的问题和解决
完整的代码如下
/** * 解决了 参数中包含 空格和脚本没有执行权限的问题 * @param scriptPath 脚本路径 * @param para 参数数组 */ private void execShell(String scriptPath, String ... para) { try { String[] cmd = new String[]{scriptPath}; //为了解决参数中包含空格 cmd=ArrayUtils.addAll(cmd,para); //解决脚本没有执行权限 ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "755",scriptPath); Process process = builder.start(); process.waitFor(); Process ps = Runtime.getRuntime().exec(cmd); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } //执行结果 String result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } }
源码位置:
https://github.com/527515025/JavaTest/tree/master/src/main/java/com/us/callShell
参考://www.jb51.net/article/61529.htm
总结