Skip to main content

Posts

Showing posts from December 26, 2016

Apache Commons Exec API for executing exe files from java program

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 c...

API for executing exe files from java program.

The traditional API for calling the executable in java program is using the Runtime, Process and their methods like exec(command), waitFor() methods respectively. a simple example to execute a notepad.exe from java program using the above API is given below. Process process = Runtime.getRuntime().exec("notepad.exe"); the above code is used to launch the notepad.exe executable from java program. if there are multiple commands needs to be passed then the code would be.... String[] command = {"cmd.exe", "/C", "echo ", "%TEMP%"};  Process process = Runtime.getRuntime().exec(command); the above snippet is used to execute multiple commands in a java program. this code prints the environment variable TEMP on to the console. Handling standard output produced by the above code: BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String output = ""; String line = ...