Java Program to open the command prompt and insert commands
Last Updated :
19 Jun, 2017
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 :
Share your thoughts in the comments
Please Login to comment...