Tuesday, November 8, 2016

Run/Monitor external program using Java

You can run/monitor external programs using Java. These are very useful when your software is dependent on any third party tool.I used this technique when I needed to write a cd using Java.

In this tutorial we will take a simple example where we will :

1) List current process from task manager
2) Play music with Java
3) Run external program without console window

Language Used:
Java

Code:
Please find the code at https://github.com/csanuragjain/extra/tree/master/ExternalProgramRunner

Explanation:

Main Method:
      public static void main(String[] args) throws InterruptedException, IOException {  
           //open and list process from task manager  
           String[] commands = {"tasklist.exe"};  
           new RunExternalProgram().runProgram(commands);  
           //Play song which is at c:\\Program Files\\1.mp3  
           String[] commands2 = {"\"c:\\Program Files\\Windows Media Player\\wmplayer.exe\"","\"c:\\Program Files\\1.mp3\""};  
           new RunExternalProgram().runProgram(commands2);  
           //Run program with hidden console  
           String[] commands3 = {"cmd","/c","start","/B","notepad"};  
           new RunExternalProgram().runProgram(commands3);  
      }  


How it works:
1) We define a variable holding the command to run. Tasklist.exe in windows gives name of all current process.
2) We call the function runProgram passing the argument as the required command to be run
3) if we wish to run media player we pass the command as <path to media player> <file to play>
4) If we have any external bat which we want to run using Java and we dont wish to show console window to user then we can use the switch /B. Here we opened notepad such that user wont see the console window.

runProgram Method:
  public void runProgram(String[] program) throws InterruptedException, IOException  
  {  
  Process proc = Runtime.getRuntime().exec (program);  
  InputStream progOutput = proc.getInputStream ();  
  InputStreamReader inputReader=new InputStreamReader(progOutput);  
  BufferedReader reader = new BufferedReader(inputReader);   
  String line;  
  while ((line = reader.readLine()) != null)  
    {  
   System.out.println(line);  
    }  
  if (0 == proc.waitFor ()) {  
    System.out.println("Process completed successfully");  
  }  
  else  
  {  
   System.out.println("Their was some issue while running the program");  
  }  
  }  


How it works:
1) Runtime.getRuntime.exec runs any command which is passed as argument and returns the new process created
2) Process can write some information like tasklist.exe list all the process, so to obtain the values returned by process, we call getInputStream on the process
3) We read all the lines printed by process and write the same to System console
4) proc.waitFor () will return value when the process is complete. It returns 0 if process was successful otherwise gives value!=0

Full Code:
 package com.cooltrickshome;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 public class RunExternalProgram {  
      /**  
       * @param args  
       * @throws IOException   
       * @throws InterruptedException   
       */  
      public static void main(String[] args) throws InterruptedException, IOException {  
           //open and list process from task manager  
           String[] commands = {"tasklist.exe"};  
           new RunExternalProgram().runProgram(commands);  
           //Play song which is at c:\\Program Files\\1.mp3  
           String[] commands2 = {"\"c:\\Program Files\\Windows Media Player\\wmplayer.exe\"","\"c:\\Program Files\\1.mp3\""};  
           new RunExternalProgram().runProgram(commands2);  
           //Run program with hidden console  
           String[] commands3 = {"cmd","/c","start","/B","notepad"};  
           new RunExternalProgram().runProgram(commands3);  
      }  
      public void runProgram(String[] program) throws InterruptedException, IOException  
      {  
           Process proc = Runtime.getRuntime().exec (program);  
           InputStream progOutput = proc.getInputStream ();  
           InputStreamReader inputReader=new InputStreamReader(progOutput);  
           BufferedReader reader = new BufferedReader(inputReader);            
           String line;  
           while ((line = reader.readLine()) != null)  
             {  
                     System.out.println(line);  
             }  
           if (0 == proc.waitFor ()) {  
             System.out.println("Process completed successfully");  
           }  
           else  
           {  
                System.out.println("Their was some issue while running the program");  
           }  
      }  
 }  

Hope it helps :)

No comments:

Post a Comment