- 官網(wǎng): Apache Commons Exec ?
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
作用:在java程序中開(kāi)啟進(jìn)程執(zhí)行外部程序龄糊。
-
使用舉例:
- 1.在java程序中開(kāi)啟打印機(jī)程序打印文件。
- 2.在java程序中執(zhí)行外部腳本程序日丹。
java支持:
java提供了Runtime.exec() API來(lái)調(diào)用外部程序剿另,Apache Commons Exec只是對(duì)其進(jìn)行了封裝刁赖。優(yōu)點(diǎn):(提供了對(duì)開(kāi)啟進(jìn)程的管理)
提供watchdog(看門(mén)狗)關(guān)閉掛起的進(jìn)程壳炎。(比如打印機(jī)程序缺少紙图贸,但是程序會(huì)處于阻塞狀態(tài)無(wú)法結(jié)束)
通過(guò)ExecuteResultHandler提供了異步執(zhí)行外部程序的能力。默認(rèn)是同步冕广。
使用更方便。
我的案例:
- 在程序中執(zhí)行本來(lái)通過(guò)run.bat腳本執(zhí)行的內(nèi)容偿洁。
在run.bat中的內(nèi)容:
spark-submit --class "SimpleApp" --master local[4] D:/study/sparkstudy/simple-project/target/simple-project-1.0.jar
- 通過(guò)程序完成run.bat腳本的內(nèi)容
- 第一種:
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");//獲取程序外部程序執(zhí)行結(jié)果
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");//獲取程序外部程序執(zhí)行結(jié)果
String error = errorStream.toString("gbk");