How to Execute Native Shell Commands from Java Program?
Last Updated :
03 Mar, 2021
A shell command is a command that we can trigger using a keyboard and a command-line or a shell instead of a Graphical user interface. Usually, we would trigger shell commands manually. However, there can be instances where this needs to be done programmatically through Java.
Java provides support to run native shell commands with two classes: RunTime and ProcessBuilder. The main disadvantage of using these classes and running shell commands from inside a Java Program is Java loses its portability.
What does losing portability mean?
Java goes by the principle "compile once, run anywhere." This means that a Java program written and compiled on one operating system can run on any other operating system without making any changes.
When we use either the ProcessBuilder or the Runtime classes to run Native shell commands, we make the Java program dependent on the underlying operating system. For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands.
Examples:
The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class.
Example 1: Loss of portability.
This example shows what happens if we execute a Java program meant for the Linux/Unix operating system on a Windows operating system.
Java
// if we execute a Java program meant for the Linux/Unix
// operating system on a Windows operating system
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellCommandRunner4 {
public static void main(String[] args)
{
try {
System.out.println(
System.getProperty("os.name"));
System.out.println();
// This process cannot be run on Windows. So the
// program will throw an exception.
ProcessBuilder pb
= new ProcessBuilder("sh", "-c", "ls");
// Exception thrown here because folder
// structure of Windows and Linux are different.
pb.directory(
new File(System.getProperty("user.home")));
// It will throw and exception
Process process = pb.start();
StringBuilder output = new StringBuilder();
BufferedReader reader
= new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(
"**************************** The Output is ******************************");
System.out.println(output);
System.exit(0);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The output of the above program when run on a Windows machine.Example 2: Run a simple shell command
This example shows how to run a simple Windows shell command. We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine.
Java
// Run a simple Windows shell command
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ShellCommandRunner {
public static void main(String[] args)
{
ProcessBuilder processBuilder
= new ProcessBuilder();
List<String> builderList = new ArrayList<>();
// add the list of commands to a list
builderList.add("cmd.exe");
builderList.add("/C");
builderList.add("tasklist | findstr chrome");
try {
// Using the list , trigger the command
processBuilder.command(builderList);
Process process = processBuilder.start();
// To read the output list
BufferedReader reader
= new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : "
+ exitCode);
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Chrome browser processes.Example 3: Run a bat file
This example shows how to run a simple .bat program in the Java console. The .bat file displays the windows system information.
Java
// Run a simple .bat program in the Java console
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellCommandRunner3 {
public static void main(String[] args)
{
try {
// File location for the bat script
File dir = new File("D:\\bat_scripts");
// Command to run the bat file in the same
// console
ProcessBuilder pb = new ProcessBuilder(
"cmd.exe", "/C", "sysinfo.bat");
pb.directory(dir);
Process process = pb.start();
StringBuilder output = new StringBuilder();
BufferedReader reader
= new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(
"**************************** The Output is ******************************");
System.out.println(output);
System.exit(0);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System info bat file program outputExample 4:Run a shell command using the RunTime class.
This example shows how to run a simple command using the RunTime class. We use the exec() method of the Runtime class.
Java
// Run a simple command using the RunTime class
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellCommandRunner2 {
public static void main(String[] args)
{
try {
Process process
= Runtime.getRuntime().exec("where java");
StringBuilder output = new StringBuilder();
BufferedReader reader
= new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(
"**************************** The Output is ******************************");
System.out.println(output);
System.exit(0);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
where java in Java program
Similar Reads
Java Program to Create a New File
There are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches.Methods to Create Files in JavaThere are two methods mentioned belowUsing the File Class
4 min read
Java Program to Read and Print All Files From a Zip File
A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Â Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip fi
4 min read
How to Read a File From the Classpath in Java?
Reading a file from the classpath concept in Java is important for Java Developers to understand. It is important because it plays a crucial role in the context of Resource Loading within applications. In Java, we can read a file from the classpath by using the Input Stream class. By loading the cla
3 min read
Java Directories Programs: Basic to Advanced
Directories are an important part of the file system in Java. They allow you to organize your files into logical groups, and they can also be used to control access to files. In this article, we will discuss some of the Java programs that you can use to work with directories. We will cover how to cr
3 min read
Java Networking Programs - Basic to Advanced
Java allows developers to create applications that can communicate over networks, connecting devices and systems together. Whether you're learning about basic connections or diving into more advanced topics like client-server applications, Java provides the tools and libraries you need. This Java Ne
3 min read
Java Program to Get CPU Serial Number for Windows Machine
CPU Serial Number (or Processor Serial Number) is a software-readable unique serial number that Intel has stamped into its Pentium 3 microprocessor. Intel offers this as a feature that can be optionally used to provide certain network management and e-commerce benefits. Basically, it lets a program
3 min read
Java Program to Get System Name for Windows and Linux Machine
We can get the System name for a Windows or Linux machine using the getHostName() method of the InetAddress class of java.net package after getting the IP address of the system using getLocalHost() method of the same class. The class InetAddress gets the IP address of any hostname. Â getLocalHost() m
1 min read
How to Find the Number of Arguments Provided at Runtime in Java?
The Java command-line argument is an argument that is passed at the time of running of a program. i.e. in order to make a program dynamic, there may be cases where we pass the arguments at runtime. Usually, via command-line arguments, they get passed and there are ways to find the number of argument
3 min read
Java Program to Convert InputStream to String
Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
4 min read
Java Program to Display all the Directories in a Directory
The directory is the organizing structure of the computer file system which is not only responsible for storing files but also to locate them on the memory. File organization structure is a hierarchical structure involving parent and child relationships just like what is there in tree data structure
3 min read