In this article, we will discuss how to run terminal commands from Java code. We can execute specific commands from the terminal to execute processes in an operating system.
The most used ones are in Linux-based operating systems. We literally do everything from the terminal in Linux to work on the server and sometimes we need to do it from the code.
ProcessBuidler
We are going to discuss ProcessBuilder.java
and Process.java
files.
Ok, let’s see one code that can execute commands from the terminal:
- The above code executes
ls
commands to list files and directories on my desktop. You can modify the path of the file to point to your desktop or any folder and try running other commands. If you are on a Windows machine of course you have to run the command that works on the Windows command prompt.
I have used ProcessBuilder
to get an instance of Process
class. ProcessBuilder is used to create operating system processes.
builder.directory(whereToRun);
We are specifying where we want to run our command. By default, it will run under this directory System.getProperty("user.dir")
if(isWindows) {
builder.command("cmd.exe", "/c", command);
}else {
builder.command("sh", "-c", command);
}
We are providing commands to execute. Notice, for Windows, we are running cmd(command prompt) and for Linux-based operating system sh(shell).
Process process = builder.start();
Once we have specified commands and the place to run we are starting a process and it returns an instance of Process
class.
The class provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process
In order to see the response from the process, we need to get them as streams. it has two types of responses. The success response is when the command executes without any errors.
InputStream inputStream = process.getInputStream();
and the stream for error output
InputStream errorStream = process.getErrorStream();
We can redirect the streams for example to write into a file or to a different stream by using the redirect method.
also, we can wait for the process to finish. In our example, we wait for 30 seconds and if it will not complete, it will return false.
boolean isFinished = process.waitFor(30, TimeUnit.SECONDS);
We can also kill the process
if(!isFinished) {
process.destroyForcibly();
}
Runtime.exec
Ok, let’s take a look at one more way of executing the commands
In this example, we didn’t use ProcessBuilder
We have used
Runtime.getRuntime().exec(commands, null, whereToRun);
But it’s actually using ProcessBuilder
as well in the exec
method.
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
Summary
It’s quite helpful to know how to run the operating system processes via Java code. The ProcessBuilder
class is used to build Process
object. We specify the commands and other configurations in the ProcessBuilder.
We work on actual execution with Process
instance. For example to get the status code from the process, to get its id, to see the output, to wait, and to kill the process.
Thank you for reading, have a wonderful day!
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET