mavenJava学习笔记我爱编程

Apache Commons Exec使用(运行外部程序)

2017-06-06  本文已影响254人  zlcook
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>

我的案例:

spark-submit   --class "SimpleApp"   --master local[4]   D:/study/sparkstudy/simple-project/target/simple-project-1.0.jar
                    String line = "spark-submit.cmd   --class \"SimpleApp\"   --master local[4]  D:\\study\\sparkstudy\\simple-project\\target\\simple-project-1.0.jar";
                   
                     CommandLine cmdLine =   CommandLine.parse(line);
                     DefaultExecutor executor = new DefaultExecutor();
                     executor.setExitValues(null);
                     ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
                     executor.setWatchdog(watchdog);

                     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                     ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
                     PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);

                     executor.setStreamHandler(streamHandler);
                     executor.execute(cmdLine);
                     String out = outputStream.toString("gbk");//获取程序外部程序执行结果
                     String error = errorStream.toString("gbk");

第二种:

                     File file = new File("D:\\study\\sparkstudy\\simple-project\\target\\simple-project-1.0.jar");
                     Map map = new HashMap();
                     map.put("FILE", file);
                     CommandLine cmdLine =  new CommandLine("spark-submit.cmd");
                     cmdLine.addArgument("--class");
                     cmdLine.addArgument("\"SimpleApp\"");
                     cmdLine.addArgument("--master");
                     cmdLine.addArgument("local[4]");
                     cmdLine.addArgument("${FILE}");
                     cmdLine.setSubstitutionMap(map);

                     DefaultExecutor executor = new DefaultExecutor();
                     executor.setExitValues(null);
                     ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
                     executor.setWatchdog(watchdog);

                     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                     ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
                     PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);
                     executor.setStreamHandler(streamHandler);
                     executor.execute(cmdLine);
                     String out = outputStream.toString("gbk");//获取程序外部程序执行结果
                     String error = errorStream.toString("gbk");
上一篇 下一篇

猜你喜欢

热点阅读