I am trying to use common-exe asynchronous way to run the batch process from java program, so that I can read and process the output stream from the batch process at runtime only.
I have learned that this piece of code runs the process asynchronously
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
CommandLine cmdLine = new CommandLine("some batch file");
Executor executor = new DefaultExecutor();
executor.execute(cmdLine, resultHandler);
But now my problem is how read the out stream from the batch file parallelly to the execution. I have to process some information from the output stream.
Here is my piece of code from which I am trying.. I am not able to figure how to resolve my problem..
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");
}
I have attained this feature with the help of SwingWorker abstract class.
This abstract class provides several API to override, those can be used to perform the task in background.
Following example shows how to execute background thread using swingworker.
Here are the links for the documentations and tutorials
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
http://en.wikipedia.org/wiki/SwingWorker
Enjoy…