我正在尝试使用 common-exe 异步方式从 java 程序运行批处理,以便我只能在运行时读取和处理批处理的输出流。
我了解到这段代码异步运行进程
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
CommandLine cmdLine = new CommandLine("some batch file");
Executor executor = new DefaultExecutor();
executor.execute(cmdLine, resultHandler);
但现在我的问题是如何从批处理文件中并行读取输出流到执行。我必须处理来自输出流的一些信息。
这是我正在尝试的一段代码..我无法弄清楚如何解决我的问题..
String command = "some batch file.bat";
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(pipedOutputStream);
CommandLine commandLine = null;
DefaultExecutor defaultExecutor = new DefaultExecutor();
DataInputStream dataInputStream = null;
DefaultExecuteResultHandler executeResultHandler = new DefaultExecuteResultHandler();
commandLine.parse(command);
try {
dataInputStream = new DataInputStream(new PipedInputStream(pipedOutputStream));
defaultExecutor.setStreamHandler(pumpStreamHandler);
defaultExecutor.execute(commandLine, executeResultHandler);
InputStream outCmdStream = null;
pumpStreamHandler.setProcessOutputStream(outCmdStream);
InputStreamReader outCmdReader = new InputStreamReader(outCmdStream);
BufferedReader outCmdBufReader = new BufferedReader(outCmdReader);
String procOutputStr;
while ((procOutputStr = dataInputStream.readLine()) != null) {
System.out.println(procOutputStr);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}