Run terminal commands from Java

Beknazar
3 min readSep 5, 2021

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!

--

--