1. java 執(zhí)行shell
java 通過 Runtime.getRuntime().exec() 方法執(zhí)行 shell 的命令或 腳本,exec()方法的參數(shù)可以是腳本的路徑也可以是直接的 shell命令
代碼如下(此代碼是存在問題的。完整代碼請看2):
/** * 執(zhí)行shell * @param execCmd 使用命令 或 腳本標(biāo)志位 * @param para 傳入?yún)?shù) */ 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. 遇到的問題和解決
完整的代碼如下
/** * 解決了 參數(shù)中包含 空格和腳本沒有執(zhí)行權(quán)限的問題 * @param scriptPath 腳本路徑 * @param para 參數(shù)數(shù)組 */ private void execShell(String scriptPath, String ... para) { try { String[] cmd = new String[]{scriptPath}; //為了解決參數(shù)中包含空格 cmd=ArrayUtils.addAll(cmd,para); //解決腳本沒有執(zhí)行權(quán)限 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"); } //執(zhí)行結(jié)果 String result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } }源碼位置:
https://github.com/527515025/JavaTest/tree/master/src/main/java/com/us/callShell
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選