Java.lang.Runtime.exec() Method

Advertisements


Description

The java.lang.Runtime.exec(String[] cmdarray) method executes the specified command and arguments in a separate process. This is a convenience method. An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).

Declaration

Following is the declaration for java.lang.Runtime.exec() method

public Process exec(String[] cmdarray)

Parameters

  • cmdarray -- array containing the command to call and its arguments.

Return Value

This method returns a new Process object for managing the subprocess

Exception

  • SecurityException -- If a security manager exists and its checkExec method doesn't allow creation of the subprocess

  • IOException -- If an I/O error occurs

  • NullPointerException -- If command is null

  • IndexOutOfBoundsException -- If cmdarray is an empty array (has length 0)

Example

This example requires a file named example.txt in our CLASSPATH with the following contents:

Hello World!

The following example shows the usage of lang.Runtime.exec() method.

package com.tutorialspoint;

public class RuntimeDemo {

   public static void main(String[] args) {
      try {

         // create a new array of 2 strings
         String[] cmdArray = new String[2];

         // first argument is the program we want to open
         cmdArray[0] = "notepad.exe";

         // second argument is a txt file we want to open with notepad
         cmdArray[1] = "example.txt";

         // print a message
         System.out.println("Executing notepad.exe and opening example.txt");

         // create a process and execute cmdArray
         Process process = Runtime.getRuntime().exec(cmdArray);

         // print another message
         System.out.println("example.txt should now open.");

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

   }
}

Let us compile and run the above program, this will produce the following result:

Executing notepad.exe and opening example.txt
example.txt should now open.



Advertisements
Advertisements