James Gosling: idealism, the Internet and Java, Pt I

Monday 26 December 2016

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 = "";

while((line = input.readLine()) != null){

System.out.println(line);

}

This Procedure is ideal when there is an executable to run without waiting for its completion of execution. despite the a method called p.waitFor() which waits until the process execution is completed, it is difficult to handle the process's standard Outputs and Inputs gracefully. and the no of lines of code also increases drastically.

the alternative to this traditional API is Apache Commons Exec  library.




No comments:

Post a Comment

Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...