Apache common exec执行外部命令

工作中需要用java调用外部命令(shell脚本,启动服务等),之前使用Runtime.getRuntime().exec调用外部程序,Runtime.getRuntime().exec是java原生态的命令,而Apache commons-exec封装一些常用的方法用来执行外部命令。例如我们想得到当前windows目录下的文件信息,在cmd命令行下的命令是dir。具体以代码示例展示2个方法实现。

第一种Runtime.getRuntime().exec

        String pl_cmd = "cmd.exe /c dir";
        Process p_pl = Runtime.getRuntime().exec(pl_cmd);
        BufferedReader br_pl = new BufferedReader(new InputStreamReader(
                p_pl.getInputStream()));
        String stdout = br_pl.readLine();
        while (stdout != null) {
            System.out.println(stdout);
            stdout = br_pl.readLine();
        }

第二种Apache commons-exec

        ByteArrayOutputStream stdout = new ByteArrayOutputStream();
        PumpStreamHandler psh = new PumpStreamHandler(stdout);
        CommandLine cl = CommandLine.parse("cmd.exe /c dir");
        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(psh);
        exec.execute(cl);
        System.out.println(stdout.toString());

代码参考github

其他工程参考链接

https://github.com/wucao/JDeploy

原文地址:https://www.cnblogs.com/xiongmaotailang/p/5289958.html