Tuesday, December 11, 2012

Java Native Processing



Native processing , is the way to invokes  the platform dependent process form the java code, Java provides the Native processing for Linux/Windows .
Example Code :
 TestApp.java
public class TestApp {
public static void main(String[]args) {
String line;
      try {
            Process process = Runtime.getRuntime().exec(“notepad.exe”);
BufferedReader is = new BufferedReader(
 new InputStreamReader(process.getInputStream()));
while ((line = is.readLine()) != null)
System.out.println(line);
System.out.println("In Main after EOF");
System.out.flush();
try {
   p.waitFor();  // wait for process to complete
 catch (InterruptedException e) {
  System.err.println(e);  // "Can'tHappen"
   return;
}
System.err.println("Process done, exit status was " + p.exitValue());
          } catch (Exception e) {
            e.printStackTrace(System.err);
          }
      }
}
Compile the above code
Javac –d TestApp.java
Run Application
Java  TestApp
It invokes the notepad application .
But some time, we need to execute the heavy process they will take time, and we may run third party tools form the command prompt so we don’t have the control on them. To get the control on them Apache foundation providing an Apache Commons Exec  API  to achieve it. This is the best API for the java development to get the outcomes of the process.

Example :
ApacheCommonExec.java
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
Public class ApacheCommonExec {
Public static void main(String args[]){
try {
      CommandLine cmdLine = CommandLine.parse(filePath);
      DefaultExecutor executor = new DefaultExecutor();
      executor.execute(cmdLine);                     
      } catch (Exception ex) {
       ex.printStackTrace();
      }
}
}
To download the library file please click Here
For more Information please click  Here

No comments:

Post a Comment