Saturday, March 19, 2011

How to create process in Java ?

To create a process in Java, you may use :
Runtime.exec() or ProcessBuilder.start()

The following samples illustrate how to use the class ProcessBuilder.

Under Windows XP, Java can create two kind of external process, namely, windows application and console application.

Sample for Windows Application
The following sample creates a process that launches the "notepad" editor and loads the program file to the editor.


/******************************************************************************
* File : WindowProcessRunner.java
* Author : http://java.macteki.com/
* Description :
*   Open notepad and load myself in the editor
* Tested with : JDK 1.6 (under windows xp)
******************************************************************************/

public class WindowProcessRunner
{
  public static void main(String[] args) throws Exception
  {
    ProcessBuilder pb = new ProcessBuilder("notepad","WindowProcessRunner.java");
    Process p=pb.start();
  }
}


Sample for Console Application


For console application, it is desirable to wait until the process finish and display the process output. The following is a simple example.

/******************************************************************************
* File : ConsoleProcessRunner.java
* Author : http://macteki.blogspot.com/
* Description :
*   ping a host and quit
* Tested with : JDK 1.6 (under windows xp)
******************************************************************************/

public class ConsoleProcessRunner
{
  public static void main(String[] args) throws Exception
  {
    // for ubuntu linux, change the following line to 
    // ProcessBuilder pb = new ProcessBuilder("ping","-c","4","www.google.com");     
    ProcessBuilder pb = new ProcessBuilder("ping","www.google.com");    
    Process p=pb.start();

    // display process output
    java.io.InputStream is=p.getInputStream();
    int BUF_SIZE=1024;
    byte[] buffer=new byte[BUF_SIZE];

    while (true)
    {
      int n=is.read(buffer);
      if (n>0) System.out.print(new String(buffer,0,n));
      if (n<0) break;
    }
  }
}

Comments are welcome.

No comments:

Post a Comment