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 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
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
Multi-Language Programming - Java Process Class, JNI and IO Multilanguage programming, as the name suggests, involves the use of more than one programming language in a single program. There are a huge number of programming languages out there and it is a common experience that we wished we could use components from other languages as well. Well, at the firs
9 min read
Java File Handling Programs Java is a programming language that can create applications that work with files. Files are containers that store data in different formats, such as text, images, videos, etc. Files can be created, read, updated, and deleted using Java. Java provides the File class from the java.io package to handle
3 min read
How to execute shell command in Ruby? Ruby is also known for its simplicity and versatile nature, it provides various methods for executing shell commands within your scripts. Whether you need to interact with the underlying operating system or automate tasks, Ruby offers several approaches to seamlessly integrate shell commands into yo
3 min read
How to Execute Shell Commands in a Remote Machine in Python? Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. Getting Started We wi
3 min read
How to Execute OS Commands in Scala? Scala is a versatile programming language. It offers smooth approaches to running OS instructions, whether or not you want to deal with documents, automate system operations, or communicate with external gear. This article focuses on discussing ways to execute OS commands in Scala. PrerequisitesInst
2 min read
How to Create a .exe File From a Java Program? In this article, we will learn how to create a .exe file from a Java program. Java is a platform-independent language, which works on the philosophy of "write Once, Run Anywhere". It simply means that if we write a Java program, we can run it on any device that has a JVM(Java Virtual Machine). Now i
5 min read
How to Run Shell Commands in Kubernetes Pods or Containers In Kubernetes, we create pods by adding an extra layer of information on containers. This Kubernetes in short is known as K8s, an open-source container orchestration tool developed by Google. It is used to orchestrate the containers for bringing Agility in software deployment through scaling, and ma
6 min read
How to Execute Commands Remotely via SSH in Android? The SSH protocol uses encryption to secure the connection between a client and a server. All user authentication, commands, output, and file transfers are encrypted to protect against attacks in the network. More often than not you would need to SSH into your cloud Virtual Machines or a remote shell
5 min read