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
class NewClass
{
public static void main(String[] args)
{
try
{
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.
class NewClass
{
public static void main(String[] args)
{
try
{
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 :
This article is contributed by Mohit Gupta_OMG 😀. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.