In my previous post http://java-gui.blogspot.in/2016/12/api-for-executing-exe-files-from-java.html you have seen using traditional java API to execute exe files from java program.
but it is proved that it is not an ideal solution for programs which handles IO operations and for async executables. you can find more advantages of Apache Commons Exec library over traditional API in the below link.
http://commons.apache.org/proper/commons-exec/index.html
Simple example that uses the Exec library:
// class to pass the command ex: cmd.exe and its arguments...
CommandLine command = new CommandLine("ping");
// arguments to the command object can be passed in 2 ways...
command.addArguments("localhost") ;
command.addArguments("-t") ;
command.addArguments("-count");
or
command.addArguments(new String[]{"-t", "-count"});
//handling the IO operations gracefully using LogOutputStream abstract class
LogOutputStream in = new LogOutputStream() {
@Override
protected void processLine(String line, int exitvalue) {
//handle the output which was produced by the process....
System.out.println(line);
}
};
PumpStreamHandler streamHandler = new PumpStreamHandler(in, in);
// Executing the command along with its arguments
DefaultExecutor executor = new DefaultExecutor();
//attaching the created shreamhandler to the executor...
executor.setStreamHandler(streamHandler);
// execution...
executor.execute(command);
the above program executes the ping command and displays the output using the standard out.
Executing the interactive executables can be found in the below link...
link
but it is proved that it is not an ideal solution for programs which handles IO operations and for async executables. you can find more advantages of Apache Commons Exec library over traditional API in the below link.
http://commons.apache.org/proper/commons-exec/index.html
Simple example that uses the Exec library:
// class to pass the command ex: cmd.exe and its arguments...
CommandLine command = new CommandLine("ping");
// arguments to the command object can be passed in 2 ways...
command.addArguments("localhost") ;
command.addArguments("-t") ;
command.addArguments("-count");
or
command.addArguments(new String[]{"-t", "-count"});
//handling the IO operations gracefully using LogOutputStream abstract class
LogOutputStream in = new LogOutputStream() {
@Override
protected void processLine(String line, int exitvalue) {
//handle the output which was produced by the process....
System.out.println(line);
}
};
PumpStreamHandler streamHandler = new PumpStreamHandler(in, in);
// Executing the command along with its arguments
DefaultExecutor executor = new DefaultExecutor();
//attaching the created shreamhandler to the executor...
executor.setStreamHandler(streamHandler);
// execution...
executor.execute(command);
the above program executes the ping command and displays the output using the standard out.
Executing the interactive executables can be found in the below link...
link
No comments:
Post a Comment