Pages

Wednesday, March 16, 2011

Running a Process from a Java Application


There may be times where we need to start a process from a java application; the process may be a batch file of a Linux shell script file. Java allows starting another process from java applications by using Process and ProcessBuilder classes.
For every java application running inside a JVM, there will be a Runtime object available. The java application can get the Runtime object of the current environment. The java program can use the runtime object to interact with the current environment. The Runtime object allows performing various operations like free memory, calling GC (), launch a new separate process and also intercept the shutdown process.
So to start a new process from the runtime object, we can use
Process process=Runtime.getRuntime().exec("notepad.exe");
The Runtime.exec() gives an instance of Process object. The Process class allows more control over the process like performing input from the process, killing process, getting the exit codes of the process e.t.c.
The ProcessBuilder provides more control in setting the environment variables, working directory before starting a process. Let see how we can execute a batch file in windows and get the output of the batch script.
Let see the sam.bat contents,
echo %1
so we print the first argument sent to the batch file. Create the file in c:/software.Now here is the java class to execute the batch file in a process from java application.
public class SampleStuff {

public static String PATH="C:\\software";
public static String PAR="jagadesh";

public static void main(String[] args) {
String line;

try {

ProcessBuilder builder=new ProcessBuilder("cmd.exe","/c","sam.bat",PAR);
builder.directory(new File(PATH));

Process process=builder.start();

BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));

while ((line = r.readLine()) != null) {
      System.out.println(line);
}
r.close();

      }catch (Exception e) {
         e.printStackTrace();
}
      }
           }

In the above sample class , we have started a ProcessBuilder giving the batch file to execute also a argument that the batch files uses .The ProcessBuilder also allows to get the output of the executed script and we can use that .We created a Buffered Reader to get the output of the  batch script. We can send as many arguments to the ProcessBuilder. We can also execute the shell script like
ProcessBuilder process=new ProcessBuilder("sh","mybat.sh","param 1","par1","par2");
We can also start process from a web application (in servlets or jsp).
So More Articles To Come, Happy Coding :-)
Read More