Java调用Shell命令和脚本

小咪咪 2022-08-22 00:03 375阅读 0赞

1.介绍

有时候我们在Linux中运行Java程序时,需要调用一些Shell命令和脚本。而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法:

  1. Process exec(String command)
  2. 在单独的进程中执行指定的字符串命令。
  3. Process exec(String[] cmdarray)
  4. 在单独的进程中执行指定命令和变量。
  5. Process exec(String[] cmdarray, String[] envp)
  6. 在指定环境的独立进程中执行指定命令和变量。
  7. Process exec(String[] cmdarray, String[] envp, File dir)
  8. 在指定环境和工作目录的独立进程中执行指定的命令和变量。
  9. Process exec(String command, String[] envp)
  10. 在指定环境的单独进程中执行指定的字符串命令。
  11. Process exec(String command, String[] envp, File dir)
  12. 在有指定环境和工作目录的独立进程中执行指定的字符串命令。

其中,其实cmdarray和command差不多,同时如果参数中如果没有envp参数或设为null,表示调用命令将在当前程序执行的环境中执行;如果没有dir参数或设为null,表示调用命令将在当前程序执行的目录中执行,因此调用到其他目录中的文件和脚本最好使用绝对路径。各个参数的含义:

  1. cmdarray: 包含所调用命令及其参数的数组。
  2. command: 一条指定的系统命令。
  3. envp: 字符串数组,其中每个元素的环境变量的设置格式为name=value;如果子进程应该继承当前进程的环境,则该参数为 null。
  4. dir: 子进程的工作目录;如果子进程应该继承当前进程的工作目录,则该参数为 null。

细心的读者会发现,为了执行调用操作,JVM会启一个Process,所以我们可以通过调用Process类的以下方法,得知调用操作是否正确执行:

  1. abstract int waitFor()
  2. 导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。

进程的出口值。根据惯例,0 表示正常终止;否则,就表示异常失败。

另外,调用某些Shell命令或脚本时,会有返回值,那么我们如果捕获这些返回值或输出呢?为了解决这个问题,Process类提供了:

  1. abstract InputStream getInputStream()
  2. 获取子进程的输入流。 最好对输入流进行缓冲。

2.调用Shell命令

这里为了说明问题,我仅用tar命令进行演示。tar命令是一个打包而不进行压缩的命令。同时,为了检查tar的调用是否被正常执行,我将调用waitFor()方法。

  1. private void callCMD(String tarName, String fileName, String... workspace){
  2. try {
  3. String cmd = "tar -cf" + tarName + " " + fileName;
  4. // String[] cmd = {"tar", "-cf", tarName, fileName};
  5. File dir = null;
  6. if(workspace[0] != null){
  7. dir = new File(workspace[0]);
  8. System.out.println(workspace[0]);
  9. }
  10. process = Runtime.getRuntime().exec(cmd, null, dir);
  11. // process = Runtime.getRuntime().exec(cmd);
  12. int status = process.waitFor();
  13. if(status != 0){
  14. System.err.println("Failed to call shell's command and the return status's is: " + status);
  15. }
  16. }
  17. catch (Exception e){
  18. e.printStackTrace();
  19. }
  20. }

注意:如果把命令放到一个String[]中时,必须把命令中每个部分作为一个元素存在String[]中,或者是把命令按照空格符分割得到的String[]。

  1. String[] cmd = {"tar", "-cf", tarName, fileName}; //right
  2. String[] cmd = {"tar -cf", tarName, fileName}; //error

为了说明dir参数的作用,我特地把该Java程序和要打包的目录hive/放在不同的目录:

  1. /root/workspace/eclipse/Test/src/edu/wzm/CallShell.java
  2. /root/experiment/hive

如果我不设置dir或设dir为null,那么fileName不得不是相对路径,最好是绝对路径:

  1. call.callCMD("/root/experiment/hive.tar", "/root/experiment/hive", null);
  2. // OR
  3. call.callCMD("/root/experiment/hive.tar", "/root/experiment/hive");

如果我设置了dir指向了hive所在的父目录就好办多了:

  1. call.callCMD("hive.tar", "hive", "/root/experiment/");

3.调用Shell脚本

Java调用Shell命令和调用Shell脚本的操作一模一样。我这里介绍另外几个方面:

  1. 给脚本传递参数;
  2. 捕获调用的输出结果;
  3. envp的使用。

给脚本传递参数,这个操作很简单,无非是把参数加到调用命令后面组成String,或String[]。

捕获调用输出信息,前面也提到过用Process.getInputStream()。不过,建议最好对输入流进行缓冲:

  1. BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

另外,envp是一个String[],并且String[]中的每一个元素的形式是:name=value。如:我的Linux系统中没有以下环境变量,但是我把它们写在Java代码中,作为envp:

  1. val=2
  2. call=Bash Shell

我要调用的Shell脚本是:/root/experiment/test.sh。

  1. #!/usr/bin/env bash
  2. args=1
  3. if [ $# -eq 1 ];then
  4. args=$1
  5. echo "The argument is: $args"
  6. fi
  7. echo "This is a $call"
  8. start=`date +%s`
  9. sleep 3s
  10. end=`date +%s`
  11. cost=$((($end - $start) * $args * $val))
  12. echo "Cost Time: $cost"

Java调用代码是:

  1. private void callScript(String script, String args, String... workspace){
  2. try {
  3. String cmd = "sh " + script + " " + args;
  4. // String[] cmd = {"sh", script, "4"};
  5. File dir = null;
  6. if(workspace[0] != null){
  7. dir = new File(workspace[0]);
  8. System.out.println(workspace[0]);
  9. }
  10. String[] evnp = {"val=2", "call=Bash Shell"};
  11. process = Runtime.getRuntime().exec(cmd, evnp, dir);
  12. // process = Runtime.getRuntime().exec(cmd);
  13. BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
  14. String line = "";
  15. while ((line = input.readLine()) != null) {
  16. System.out.println(line);
  17. }
  18. input.close();
  19. }
  20. catch (Exception e){
  21. e.printStackTrace();
  22. }
  23. }
  24. public static void main(String[] args) {
  25. // TODO Auto-generated method stub
  26. CallShell call = new CallShell();
  27. call.callScript("test.sh", "4", "/root/experiment/");
  28. }

输出:

  1. /root/experiment/
  2. The argument is: 4
  3. This is a Bash Shell
  4. Cost Time: 24

发表评论

表情:
评论列表 (有 0 条评论,375人围观)

还没有评论,来说两句吧...

相关阅读