Follow by Email

Monday, 23 May 2016

Execute batch file from Java Code using Runtime class

We can call any exe file from Java code using Runtime class, Runtime class extends Object class and introduced in JDK1.0

What docs says-

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
An application cannot create its own instance of this class.

Here we will see how to execute .exe and .bat file from javacode, for executable files we just pass file path and Runtime class will invoke it. But for batch file we have to first open supporting application i;e Command Promt and then provide path for batch file

See Java Programs for both case:


Execute .exe file from Java- 


package client;

import java.io.IOException;


public class OpenExeFile {
    public OpenExeFile() {
        super();
    }

    /**Main Method
     * @param args
     */
    public static void main(String[] args) {
        //Get Runtime object
        Runtime runtime = Runtime.getRuntime();
        try {
            //Execute specific exe file, Provide path as parameter
            runtime.exec("calc.exe"); //To open calculator

        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Execute Batch file from Java-


For this I have created a Batch file that opens Notepad
To create Batch File

  • Open a notepad and paste this line
    start "c:\windows\system32" notepad.exe


  • Click on File-- SaveAs





I saved this file in D drive of my Windows Machine, Now see code to open it from java


package client;

import java.io.IOException;


public class OpenBatchFile {
    public OpenBatchFile() {
        super();
    }

    /**Main Method
     * @param args
     */
    public static void main(String[] args) {
        //Get Runtime object
        Runtime runtime = Runtime.getRuntime();
        try {
            //Pass string in this format to open Batch file
            runtime.exec("cmd /c start D:\\OpenNotepad.bat");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Cheers :) Happy Learning

No comments :

Post a Comment