How to Run External Program in Java

From your Java program, it is possible to run other applications in your operating system. This enables you to make use of system programs and command line utilities from your Java program. Here are some typical uses of this feature when running your Java program in Windows,

  • You want to invoke a Windows program such as Notepad
  • You want to invoke a command line utility such as Check disk (chkdsk) or IP information (ipconfig)
  • You want to  access the Windows command interpreter and access some of its features such as "dir" command or "find" command. In this case, please note that the program you want to access is cmd.exe and commands like "dir" and "find" are arguments to cmd.exe. Also when directly invoked, cmd.exe doesn’t terminate. If you want cmd.exe to terminate immediately, you should pass the /C argument.

We have provided sample programs for each of the use cases above. The overall approach here is same (we will use Runtime.exec method), but there are some subtle differences you need to be aware of.

The following program demonstrates how you can execute a Windows program such as Notepad from your Java program,

/**
 * Runs external application from this Java program
 */
public class RunProgram {

    public static void main(String[] args) {
        RunProgram rp = new RunProgram();
        rp.openNotePad();
    }

    /**
     * Runs Notepad program in the Windows system. Please note that this assumes
     * you are running this program on Windows.
     */
    private void openNotePad() {
        Runtime rt = Runtime.getRuntime();
        try {
            Process p = rt.exec("notepad");
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

This following example demonstrates how you can execute a command line program in Windows from your Java program. This program will also print the results of the command. Note that in this case we are using another version of the Runtime.exec method. This program runs "ipconfig" command with /all command line argument. This would print the complete IP address configuration of the system.

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Runs another application from a Java program
 */
public class RunProgram2 {

    public static void main(String[] args) {
        RunProgram2 rp = new RunProgram2();
        rp.printIPInfo();
    }

    /**
     * Print complete IP address info using the command ipconfig /all
     */
    private void printIPInfo() {
        Runtime rt = Runtime.getRuntime();
        String[] commandAndArguments = {"ipconfig","/all"};
        try {
            Process p = rt.exec(commandAndArguments);
            String response = readProcessOutput(p);
            System.out.println(response);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Reads the response from the command. Please note that this works only
     * if the process returns immediately.
     * @param p
     * @return
     * @throws Exception 
     */
    private String readProcessOutput(Process p) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String response = "";
        String line;
        while ((line = reader.readLine()) != null) {
            response += line+"\r\n";
        }
        reader.close();
        return response;
    }
}

 

In the final example, we invoke the command line program (cmd.exe) of the Windows system and then execute commands supported by it. By default cmd.exe is blocking and to terminate it immediately you need to pass the command line option /C. The following program prints the directory listing of C drive (C:\) using the "dir" command of "cmd.exe".

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class RunProgram3 {

    public static void main(String[] args) {
        RunProgram3 rp = new RunProgram3();
        rp.getDirectoryListing();
    }

    /**
     * Runs cmd.exe from Java program and then invokes dir command to list C:\ drive.
     * The /C option is necessary for the program
     */
    private void getDirectoryListing() {
        Runtime rt = Runtime.getRuntime();
        String[] commandAndArguments = {"cmd","/C","dir","c:\\"};
        try {
            Process p = rt.exec(commandAndArguments);
            String listing = readProcessOutput(p);
            System.out.println(listing);
            //p.waitFor();
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Reads the response from the command. Please note that this works only
     * if the process returns immediately.
     * @param p
     * @return
     * @throws Exception 
     */
    private String readProcessOutput(Process p) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String response = "";
        String line;
        while ((line = reader.readLine()) != null) {
            response += line+"\r\n";
        }
        reader.close();
        return response;
    }
}

 

If you are not reading the response from the external program and if you want to wait for the external program to finish before you continue processing, you can use the Process.waitFor() method. This will block your program till the external program completes execution.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply