eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

The Process API provides a powerful way to execute operating system commands in Java. However, it has several options that can make it cumbersome to work with.

In this tutorial, we’ll take a look at how Java alleviates that with the ProcessBuilder API.

2. ProcessBuilder API

The ProcessBuilder class provides methods for creating and configuring operating system processes. Each ProcessBuilder instance allows us to manage a collection of process attributes. We can then start a new Process with those given attributes.

Here are a few common scenarios where we could use this API:

  • Find the current Java version
  • Set-up a custom key-value map for our environment
  • Change the working directory of where our shell command is running
  • Redirect input and output streams to custom replacements
  • Inherit both of the streams of the current JVM process
  • Execute a shell command from Java code

We’ll take a look at practical examples for each of these in later sections.

But before we dive into the working code, let’s take a look at what kind of functionality this API provides.

2.1. Method Summary

In this section, we’re going to take a step back and briefly look at the most important methods in the ProcessBuilder class. This will help us when we dive into some real examples later on:

  • ProcessBuilder(String... command)

    To create a new process builder with the specified operating system program and arguments, we can use this convenient constructor.

  • directory(File directory)

    We can override the default working directory of the current process by calling the directory method and passing a File object. By default, the current working directory is set to the value returned by the user.dir system property.

  • environment()

    If we want to get the current environment variables, we can simply call the environment method. It returns us a copy of the current process environment using System.getenv() but as a Map.

  • inheritIO()

    If we want to specify that the source and destination for our subprocess standard I/O should be the same as that of the current Java process, we can use the inheritIO method.

  • redirectInput(File file), redirectOutput(File file), redirectError(File file)

    When we want to redirect the process builder’s standard input, output and error destination to a file, we have these three similar redirect methods at our disposal.

  • start()

    Last but not least, to start a new process with what we’ve configured, we simply call start().

We should note that this class is NOT synchronized. For example, if we have multiple threads accessing a ProcessBuilder instance concurrently then the synchronization must be managed externally.

3. Examples

Now that we have a basic understanding of the ProcessBuilder API, let’s step through some examples.

3.1. Using ProcessBuilder to Print the Version of Java

In this first example, we’ll run the java command with one argument in order to get the version.

Process process = new ProcessBuilder("java", "-version").start();

First, we create our ProcessBuilder object passing the command and argument values to the constructor. Next, we start the process using the start() method to get a Process object.

Now let’s see how to handle the output:

List<String> results = readOutput(process.getInputStream());

assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));

int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);

Here we’re reading the process output and verifying the contents is that we expect. In the final step, we wait for the process to finish using process.waitFor().

Once the process has finished, the return value tells us whether the process was successful or not.

A few important points to keep in mind:

  • The arguments must be in the right order
  • Moreover, in this example, the default working directory and environment are used
  • We deliberately don’t call process.waitFor() until after we’ve read the output because the output buffer might stall the process
  • We’ve made the assumption that the java command is available via the PATH variable

3.2. Starting a Process With a Modified Environment

In this next example, we’re going to see how to modify the working environment.

But before we do that let’s begin by taking a look at the kind of information we can find in the default environment:

ProcessBuilder processBuilder = new ProcessBuilder();        
Map<String, String> environment = processBuilder.environment();
environment.forEach((key, value) -> System.out.println(key + value));

This simply prints out each of the variable entries which are provided by default:

PATH/usr/bin:/bin:/usr/sbin:/sbin
SHELL/bin/bash
...

Now we’re going to add a new environment variable to our ProcessBuilder object and run a command to output its value:

environment.put("GREETING", "Hola Mundo");

processBuilder.command("/bin/bash", "-c", "echo $GREETING");
Process process = processBuilder.start();

Let’s decompose the steps to understand what we’ve done:

  • Add a variable called ‘GREETING’ with a value of ‘Hola Mundo’ to our environment which is a standard Map<String, String>
  • This time, rather than using the constructor we set the command and arguments via the command(String… command) method directly.
  • We then start our process as per the previous example.

To complete the example, we verify the output contains our greeting:

List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("Hola Mundo")));

3.3. Starting a Process With a Modified Working Directory

Sometimes it can be useful to change the working directory. In our next example we’re going to see how to do just that:

@Test
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() 
  throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls");

    processBuilder.directory(new File("src"));
    Process process = processBuilder.start();

    List<String> results = readOutput(process.getInputStream());
    assertThat("Results should not be empty", results, is(not(empty())));
    assertThat("Results should contain directory listing: ", results, contains("main", "test"));

    int exitCode = process.waitFor();
    assertEquals("No errors should be detected", 0, exitCode);
}

In the above example, we set the working directory to the project’s src dir using the convenience method directory(File directory). We then run a simple directory listing command and check that the output contains the subdirectories main and test.

3.4. Redirecting Standard Input and Output

In the real world, we will probably want to capture the results of our running processes inside a log file for further analysis. Luckily the ProcessBuilder API has built-in support for exactly this as we will see in this example.

By default, our process reads input from a pipe. We can access this pipe via the output stream returned by Process.getOutputStream().

However, as we’ll see shortly, the standard output may be redirected to another source such as a file using the method redirectOutput. In this case, getOutputStream() will return a ProcessBuilder.NullOutputStream.

Let’s return to our original example to print out the version of Java. But this time let’s redirect the output to a log file instead of the standard output pipe:

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");

processBuilder.redirectErrorStream(true);
File log = folder.newFile("java-version.log");
processBuilder.redirectOutput(log);

Process process = processBuilder.start();

In the above example, we create a new temporary file called log and tell our ProcessBuilder to redirect output to this file destination.

In this last snippet, we simply check that getInputStream() is indeed null and that the contents of our file are as expected:

assertEquals("If redirected, should be -1 ", -1, process.getInputStream().read());
List<String> lines = Files.lines(log.toPath()).collect(Collectors.toList());
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));

Now let’s take a look at a slight variation on this example. For example when we wish to append to a log file rather than create a new one each time:

File log = tempFolder.newFile("java-version-append.log");
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(Redirect.appendTo(log));

It’s also important to mention the call to redirectErrorStream(true). In case of any errors, the error output will be merged into the normal process output file.

We can, of course, specify individual files for the standard output and the standard error output:

File outputLog = tempFolder.newFile("standard-output.log");
File errorLog = tempFolder.newFile("error.log");

processBuilder.redirectOutput(Redirect.appendTo(outputLog));
processBuilder.redirectError(Redirect.appendTo(errorLog));

3.5. Inheriting the I/O of the Current Process

In this penultimate example, we’ll see the inheritIO() method in action. We can use this method when we want to redirect the sub-process I/O to the standard I/O of the current process:

@Test
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello");

    processBuilder.inheritIO();
    Process process = processBuilder.start();

    int exitCode = process.waitFor();
    assertEquals("No errors should be detected", 0, exitCode);
}

In the above example, by using the inheritIO() method we see the output of a simple command in the console in our IDE.

In the next section, we’re going to take a look at what additions were made to the ProcessBuilder API in Java 9.

3.6. Passing Parameters Containing Spaces

When working with the ProcessBuilder API, we may need to pass arguments that contain spaces, such as strings with multiple words or file paths under directories. If not handled correctly, these arguments can cause the command to fail or be misinterpreted by the operating system.

ProcessBuilder expects each argument to be passed as a separate string in the constructor. For example, to execute:

echo "Hello World from Baeldung"

We should pass “echo” and “Hello World from Baeldung” as separate arguments, rather than as a single combined string. Here’s a unit test demonstrating this:

@Test
public void givenProcessBuilder_whenPassingArgsWithSpaces_thenSuccess() throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "echo", "Hello World from Baeldung");
    Process process = processBuilder.start();
    List<String> results = readOutput(process.getInputStream());

    assertFalse(results.isEmpty(), "Results should not be empty");
    assertTrue(results.get(0).contains("Hello World from Baeldung"));
}

In this example, we pass the command and each argument as separate strings to the ProcessBuilder constructor. The API automatically handles arguments containing spaces, so there’s no need to add quotes manually.

If we instead tried to pass the entire command as a single string, it would fail because ProcessBuilder would interpret it as the executable name rather than a command with arguments.

We should keep in mind a few best practices when working with arguments containing spaces:

  • We always split the executable and each argument into individual string values.
  • We avoid manually quoting arguments, since ProcessBuilder already handles this correctly for the target operating system.
  • When working with file paths that contain spaces, we pass the full path as a single argument string. We let ProcessBuilder manage the necessary escaping and avoid breaking the path into separate parts.

4. Java 9 Additions

Java 9 introduced the concept of pipelines to the ProcessBuilder API:

public static List<Process> startPipeline​(List<ProcessBuilder> builders)

Using the startPipeline method we can pass a list of ProcessBuilder objects. This static method will then start a Process for each ProcessBuilder. Thus, creating a pipeline of processes which are linked by their standard output and standard input streams.

For example, if we want to run something like this:

find . -name *.java -type f | wc -l

What we’d do is create a process builder for each isolated command and compose them into a pipeline:

@Test
public void givenProcessBuilder_whenStartingPipeline_thenSuccess()
  throws IOException, InterruptedException {
    List builders = Arrays.asList(
      new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), 
      new ProcessBuilder("wc", "-l"));

    List processes = ProcessBuilder.startPipeline(builders);
    Process last = processes.get(processes.size() - 1);

    List output = readOutput(last.getInputStream());
    assertThat("Results should not be empty", output, is(not(empty())));
}

In this example, we’re searching for all the java files inside the src directory and piping the results into another process to count them.

To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements.

5. Conclusion

To summarize, in this tutorial, we’ve explored the java.lang.ProcessBuilder API in detail.

First, we started by explaining what can be done with the API and summarized the most important methods.

Next, we took a look at a number of practical examples. Finally, we looked at what new additions were introduced to the API in Java 9.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)