zoukankan      html  css  js  c++  java
  • Java中执行外部命令

    在项目中执行一个linux的shell脚本,于是需要在java环境下执行外部命令如系统命令、linux命令的需求,本人小小研究了一下,又上网查了一些资料先整理如下。

    java执行外部命令主要依赖两个类Process和Runtime。

    一、Process类

    ProcessBuilder.start()创建一个本机进程,并返回一个Process子类的一个实例,该实例可以获取进程的相关信息,也可以控制进程。这个进程没有自己的终端,它的操作结果io都重定向到了它的父进程,父进程通过getInputStream(),getOutputStream(),getErrorStream()为子进程提供输入和获取输出,而对于io流如果有缓冲大小限制,则可能出现阻塞,导致死锁情况。

    可使用destory()方式强制杀掉子进程,exitValue()返回执行结果,如果子进程需要等待返回,调用waitFor()方法将当前线程等待,直到子进程退出。

    二、Runtime类

    Runtime.getRuntime().exec() 获得的就是Process类,exec()方法有多个重载可以使用,针对不同的情况设置不同的参数。另外需要注意的是执行的windows和linux的明林的写法是不同的。

    public class runtimeTest {

         public static void main(String[] args) {
              String command = "notepad.exe txt.txt";

            try {
                 Process process = Runtime.getRuntime().exec(command);
                 BufferedInputStream bis = new BufferedInputStream(
                         process.getInputStream());
                 BufferedReader br = new BufferedReader(new InputStreamReader(bis));
                 String line;
                 while ((line = br.readLine()) != null) {
                     System.out.println(line);
                 }

                 process.waitFor();
                 if (process.exitValue() != 0) {
                     System.out.println("error!");
                 }

                 bis.close();
                 br.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             } catch (InterruptedException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }

         }

    } 

    三、Apache Common-Exec 

    强烈建议使用apache的第三方库,该库提供了更加详细的设置和监控方法等等。

    执行的命令被称为CommandLine,可使用该类的addArgument()方法为其添加参数,parse()方法将你提供的命令包装好一个可执行的命令。命令是由执行器Executor类来执行的,DefaultExecutor类的execute()方法执行命令,exitValue也可以通过该方法返回接收。设置ExecuteWatchdog可指定进程在出错后多长时间结束,这样有效防止了run-away的进程。此外common-exec还支持异步执行,Executor通过设置一个ExecuteResultHandler类,该类的实例会接收住错误异常和退出代码。

     CommandLine cmdLine = new CommandLine("AcroRd32.exe");

    cmdLine.addArgument("/p");
    cmdLine.addArgument("/h");
    cmdLine.addArgument("${file}");
    HashMap map = new HashMap();
    map.put("file", new File("invoice.pdf"));
    commandLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    // some time later the result handler callback was invoked so we
    // can safely request the exit value
    int exitValue = resultHandler.waitFor();

     以上是自己从common-exec官方文档自己的理解,如有错误望轻拍!

  • 相关阅读:
    js取当前时间的秒级时间戳
    微信自动聊天脚本
    小程序 缓存过期问题
    去掉表格默认样式
    css3 画心
    数据导入(二):MapReduce
    数据导入(一):Hive On HBase
    HBase参数优化
    Hadoop运维手记
    HBase优化相关
  • 原文地址:https://www.cnblogs.com/kingcucumber/p/3180146.html
Copyright © 2011-2022 走看看