也许在某种情况下,Java程序需要调用shell脚本才能完成, 比如为了从其他服务器上下载一些文件,但是却不能使用普通的sftp代码完成,需要使用到证书, 这时shell脚本就比较方便 在这里我写了一个工具类,是为了调用shell脚本的。代码如下:
public class JaveShellUtil {
public static int ExecCommand(String command) { int retCode = 0; try { Process process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command }, null, null); retCode = process.waitFor(); ExecOutput(process); } catch (Exception e) { retCode = -1; } return retCode; } public static boolean ExecOutput(Process process) throws Exception { if (process == null) { return false; } else { InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; String output = ""; while ((line = input.readLine()) != null) { output += line + "\n"; } input.close(); ir.close(); if (output.length() > 0) { } } return true; } }
public class MyShell { public static void main(String[] args) { String command="cfg/demo.sh"; //需要传递的就是shell脚本的位置 int retCode=JaveShellUtil.ExecCommand(command); System.out.println(retCode+"retCode"); if(retCode==0){ System.out.println("success....."); }else{ System.out.println("error....."); } } }
(2)传递参数,为了在shell脚本中获得对应的参数,比如使用shell脚本创建某一个时间的文件夹时
package com.zhou.dado.sehll; import com.zhou.dado.util.JaveShellUtil; public class MyShell { public static void main(String[] args) { String command="cfg/demo.sh"; //需要传递的就是shell脚本的位置,参数的话每一个之间需要使用空格隔开,务必 int retCode=JaveShellUtil.ExecCommand(command+" "+"zhoudado"+" "+"barnamefile"+" "+"bxmnamefile"); System.out.println(retCode+"retCode"); if(retCode==0){ System.out.println("success....."); }else{ System.out.println("error....."); } } }
注:在传递参数时,command后面必须要有一个空格,也就是说每个的参数后面都需要有一个空格才可以,我这里是传递了三个参数
#!/usr/bin/env bash param1=$1 param2=$2 param3=$3 basepath="/app/app/$param1" mkdir -p $basepath
注意:执行shell脚本是通过java的Runtime.getRuntime().exec()方法调用的。这种调用方式可以达到目的,但是他在java虚拟机中非常消耗资源,即使外部命令本身能很快执行完毕,频繁调用时创建进程的开销也非常可观。java虚拟机执行这个命令的过程是:首先克隆一下和当前虚拟机拥有一样环境变量的进程,再用这个新的进程去执行外部命令,最后在退出这个进程,如果频繁执行这个操作,系统的消耗会很大,不仅是CPU,内存的负担也很重。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/205250.html原文链接:https://javaforall.net
