Pages

13 January 2011

Process Builder Demo

In order to create operating system processes (even another java application), running a command, and defining an environment variable; a simple approach is succeeded by using "java.lang.ProcessBuilder" class in Java.

Process process = Runtime.getRuntime().exec("cmd /c java -cp bin B");
BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while( (line = inputStream.readLine()) != null) {
 // inputStream is enabling this thread(main method) 
 // to read "System.out" prints of started process (B.main method)
 System.out.println("#read from inputStream: " + line);
}

The above example illustrates how to start a java application from another one. /c option has vital importance since the rest of the parameters that command line is fed to run them properly. java command must be in environment variables to run B (which consists the "main(String[] args)" method) and -cp is standart java parameter that indicates the classpath. inputStream variable reads the inputs that comes from the java process B which simply outputs to System.out.

In principle, the below lines of java code executes the same process; but also it enables the developer to run the command instance (pb) more than once.

ProcessBuilder pb = new ProcessBuilder("cmd","/c","java","-cp","bin","B");
Process process = pb.start();

Another usage is running an non java application from a java application is more simple than running a java application. For instance, runing notepad.exe on windows NT is as seen below.
try {
 // ...
 Process process = Runtime.getRuntime().exec("notepad.exe");
 // ...
} catch (Exception e) { 
 System.err.println(e.getMessage());
}

Third but not least, environment variables of operating system (in windows: Computer>Properties>Advance>Environment Settings) can be accessible from a java application with using environment method of ProcessBuilder. Manipulating of this map, reflecting directly to operating system environment variables set.
ProcessBuilder pb = new ProcessBuilder("something");
Map<String,String> env = pb.environment();
Set<String> keys = env.keySet();
if (keys != null) {
 for (String key : keys) {
  System.out.println(key+":"+env.get(key));
 }
}

ProcessBuilder is a powerful tool to manage specific aspects of operating system from a system independent and abstract point of view.

Download Sources
Download this page in PDF Format

Join 4Shared Now!

5 comments:

  1. THANKS!!
    But how create a subprocess using processbuilder class ?

    ReplyDelete
  2. The ProcessBuilder.start() method is invoked to create new subprocesses.

    ReplyDelete
  3. I want to run java program from another java program. It works fine with using Runtime exec, however after doing some search I found out that processbuilder is better approach,since I need to handle output,input and error streams of the process.How to do this using processbuilder?
    Process p1 = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
    + "C:/Users/Dinara/Desktop/D/src/test.java");
    Process p2 = Runtime.getRuntime().exec(System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test");

    ReplyDelete
  4. Could you please help, how to run java program from another java program using ProcessBuilder? I did it using Runtime exec and it works ok. However after searching the Internet I found out that ProcessBuilder is better approach, since I need to handle output, input and error streams of the process.
    Process p1 = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
    + "C:/Users/Dinara/Desktop/D/src/test.java");
    Process p2 = Runtime.getRuntime().exec(System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test");

    ReplyDelete
  5. HI
    I am using the below code to run a command : "testrunner.bat -r -a -j -f" + "C:/DEMO" + " -I -S -t " + "\"C:/Documents and Settings/n415554/soapui-settings.xml\"" + " -i " + "\"C:/Documents and Settings/n415554/Desktop/RUN_INSCFC-FEI-soapui-project.xml\"";

    and it will take around 5 to 10 mins to complete to run the batch file.
    --- Heere the proble is that.. I could able to run the batch file once i terminat the mail class. Please let me know any issue with this code.



    String s = "testrunner.bat -r -a -j -f" + "C:/DEMO" + " -I -S -t " + "\"C:/Documents and Settings/n415554/soapui-settings.xml\"" + " -i " + "\"C:/Documents and Settings/n415554/Desktop/RUN_INSCFC-FEI-soapui-project.xml\"";

    String[] command = {"CMD", "/C", s};
    ProcessBuilder probuilder = new ProcessBuilder( command );
    //You can set up your work directory
    probuilder.directory(new File("c:\\soapUI-4.0.0.b\\bin"));
    // c:\\soapUI-4.0.0.b\\bin for c:\\xyzwsdemo
    Process process = probuilder.start();
    //Read out dir output
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    System.out.printf("Output of running %s is:\n",Arrays.toString(command));

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

    //Wait to get exit value
    try {
    int exitValue = process.waitFor();
    System.out.println("\n\nExit Value is " + exitValue);
    }
    catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace(); }
    }

    ReplyDelete

Thx for reading! Comments are appreciated...