Open In App

Java Program to open the command prompt and insert commands

Improve
Improve
Like Article
Like
Save
Share
Report

This article aims to provide you a simple code to open Command Prompt and how you can insert the commands in it using Java language.

Here we will use Runtime class of java.lang Package. This class allows Java application to interfere with the environment in which it is running as each and every Java application has an instance of Runtime class. To perform the task, let us have a look at exec() method of Runtime class.

java.lang.Runtime.exec(String command) : methods plays a major role in executing the specified string command.It executes the specified string command in a separate process.

Syntax: 
public Process exec(String command)
Parameters : 
command : specific command
Returns :
A new Process object for managing the subprocess
Throws:
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
IllegalArgumentException - If command is empty

How to run Command Prompt




// Java program to illustrate
// open cmd prompt
  
class NewClass
{
    public static void main(String[] args)
    {
        try
        {
            // Just one line and you are done ! 
            // We have given a command to start cmd
            // /K : Carries out command specified by string
           Runtime.getRuntime().exec(new String[] {"cmd", "/K", "Start"});
  
        }
        catch (Exception e)
        {
            System.out.println("HEY Buddy ! U r Doing Something Wrong ");
            e.printStackTrace();
        }
    }
}


Note :
This program won’t run on Online-IDE, so please run it on your system JAVA compiler and see the working.
Output :

Insert and run the command

Using this code you can perform certain commands in cmd. Given program executes the “dir”( list all directories) and “ping”(test the ability of the source computer to reach a specified destination computer) command in cmd.




// Java program to illustrate
// executing commands on cmd prompt
  
class NewClass
{
    public static void main(String[] args)
    {
        try
        
         // We are running "dir" and "ping" command on cmd
         Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"dir && ping localhost\"");
        }
        catch (Exception e)
        {
            System.out.println("HEY Buddy ! U r Doing Something Wrong ");
            e.printStackTrace();
        }
    }
}


Note :
This program won’t run on Online-IDE, so please run it on your system JAVA compiler and see the working.
Output :



Last Updated : 19 Jun, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads