It's all about Java: executable
Showing posts with label executable. Show all posts
Showing posts with label executable. Show all posts

Monday, 26 December 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 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


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.




Sunday, 3 July 2011

Controlling an executable from Java program


Windows tools like Notepad, internet explorer and other executable files can be started from java program through its core API.


Procedure to start a Notepad application from java program:

 Create an object for Runtime class
                         Runtime runtime = Runtime.getRuntime();
       
Create the command string
                         String command = "notepad.exe";        
Call exec()
                         try{
                             Process process = runtime.exec(command);
                         }catch(IOException e){
                     
                         }
         For starting Notepad application does not require Process object, but few executables requires I/O operation. In that case we will have to use the process object exclusively.

Simple program which starts Notepad:


                                                                         Fig-1.01


Procedure to start Browser in java Program:

We have seen starting a notepad application from java program, now let us start Internet Explorer with some URL.

The command string varies depending upon the OS and  Browser we are using.

1. Identify current Operating System and Browser:
                                               
        public boolean isWindowsPlatform() {
     
          String OS = System.getProperty("os.name");
          if(OS != null && OS.startsWith(WIN_ID)) {
              return true;
          }else{
              return false;
          }
    }

2. Create FLAG and PATH:
     
        Windows OS:
               Flag is used to display the URL:
                         String WIN_FLAG = "url.dll,FileProtocolHandler";
               Path is used to open the default browser:
                         String WIN_PATH = "rundll32"
                URL:
                          http://www.java.com
         Unix OS:
               Flag to display the URL:
                        String UNIX_FLAG = "-remote openURL";
               To open Netscape Navigator:
                        String UNIX_PATH = "netscape"
               URL:
                         http://www.java-gui.blogspot.com
3. Create Command String:
     
         String command = WIN_PATH+" "+WIN_FLAG+" "+URL; [windows platform]

4.  Create Runtime object and execute the command:
        Runtime runtime = Runtime.getRuntime();
          try {
                 runtime.exec(command);
          } catch(Exception e){
              e.printStackTrace();
          }

Complete program to start Browser:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class StartBrowser {

    public StartBrowser(String URL) {

       String command = null;
        // check OS
       if(isWindowsPlatform()) {

         // create command string
         command = WIN_PATH+" "+WIN_FLAG+" "+URL;
         //pass command to the exec()
         Runtime runtime = Runtime.getRuntime();
         try {
              runtime.exec(command);
         } catch(Exception e){e.printStackTrace();}
       }
    }

    public boolean isWindowsPlatform() {
        String OS = System.getProperty("os.name");
        if(OS != null && OS.startsWith(WIN_ID)) {
            return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
         new StartBrowser("http://www.java-gui.blogspot.com");
    }

    private static final String WIN_ID = "Windows";
    // default browser start from windows.
    private static final String WIN_PATH = "rundll32";
    // The flag to display a url.
    private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
}

Popular posts

Atomicity with Java Programming Language

 Atomicity with Java What is Atomicity Atomicity, in computer science, is considered to be a property [ALL-OR-NOTHING], that the state of a ...