首页 > Web开发 > 详细

Apache common exec执行外部命令

时间:2016-03-18 00:14:39      阅读:342      评论:0      收藏:0      [点我收藏+]

工作中需要用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

Apache common exec执行外部命令

原文:http://www.cnblogs.com/xiongmaotailang/p/5289958.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!