http://www.rgagnon.com/javadetails/java-0014.html

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;

public class CmdExec {

public static void main(String args[]) {
    try {
        // enter code here

        Process p = Runtime.getRuntime().exec(
            Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()
        );

        // enter code here

        try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;

            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
        }

    } catch (Exception err) {
        err.printStackTrace();
    }
  }
}

You can get the local path using System properties or a similar approach.

http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html

Answer from James P. on Stack Overflow
Top answer
1 of 3
38

http://www.rgagnon.com/javadetails/java-0014.html

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;

public class CmdExec {

public static void main(String args[]) {
    try {
        // enter code here

        Process p = Runtime.getRuntime().exec(
            Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()
        );

        // enter code here

        try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;

            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
        }

    } catch (Exception err) {
        err.printStackTrace();
    }
  }
}

You can get the local path using System properties or a similar approach.

http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html

2 of 3
31

The Java Class Library represents external processes using the java.lang.Process class. Processes can be spawned using a java.lang.ProcessBuilder:

Process process = new ProcessBuilder("processname").start();

or the older interface exposed by the overloaded exec methods on the java.lang.Runtime class:

Process process = Runtime.getRuntime().exec("processname");

Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object. If you need to check that the process has finished (or wait for it to finish), don't forget to check that the exit value (exit code) returned by process.exitValue() or process.waitFor() is as expected (0 for most programs), since no exception is thrown if the process exits abnormally.

Also note that additional code is often necessary to handle the process's I/O correctly, as described in the documentation for the Process class (emphasis added):

By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

One way to make sure that I/O is correctly handled and that the exit value indicates success is to use a library like jproc that deals with the intricacies of capturing stdout and stderr, and offers a simple synchronous interface to run external processes:

ProcResult result = new ProcBuilder("processname").run();

jproc is available via maven central:

<dependency>
      <groupId>org.buildobjects</groupId>
      <artifactId>jproc</artifactId>
      <version>2.5.1</version>
</dependency>
🌐
Baeldung
baeldung.com › home › java › core java › guide to java.lang.process api
Guide to java.lang.Process API | Baeldung
June 10, 2025 - The Process class provides methods for interacting with these processes, including extracting output, performing input, monitoring the lifecycle, checking the exit status, and destroying (killing) it. First, let’s see an example to compile and run another Java program with the help of the ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Process.html
Process (Java Platform SE 8 )
April 21, 2026 - Java™ Platform Standard Ed. 8 ... The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - The Runtime class's exec() method is your key to making your Java application interact with the operating system, if you've ever wanted it to.
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - In this article, we’ll learn how to execute a shell command from Java applications. First, we’ll use the .exec() method the Runtime class provides. Then, we’ll learn about ProcessBuilder, which is more customizable.
🌐
Medium
mustafa-aydogan.medium.com › how-to-run-a-command-from-java-fe6b942b98a
How to Run a Command from Java. Sometimes, you may want to run a… | by Mustafa Aydoğan | Medium
September 27, 2025 - In this example, we create a ProcessBuilder object with the command ls, set the working directory to /tmp, and redirect the output to the standard output stream of the Java process. We then start the new process and wait for it to finish using the waitFor method. Finally, we print the exit code of the process to the console. In conclusion, the ProcessBuilder class provides a simple and powerful way to run commands from a Java process.
🌐
DZone
dzone.com › coding › java › running a java class as a subprocess
Running a Java Class as a Subprocess
May 21, 2019 - How the process finished is detailed by its exitValue. For example, 0 normally denotes a successful execution and 1 details an invalid syntax error. There are many other exit codes and they can all vary between applications. Calling the exec method would look something like the below: JavaProcess.exec(MyProcess.class, List.of("-Xmx200m"), List.of("argument"))
🌐
GeeksforGeeks
geeksforgeeks.org › java › calling-external-program-java-using-process-runtime
Calling an External Program in Java using Process and Runtime - GeeksforGeeks
July 23, 2025 - Java contains the functionality of initiating an external process - an executable file or an existing application on the system, such as Google Chrome or the Media Player- by simple Java code. One way is to use following two classes for the purpose: ... Runtime class The Process class present in the java.lang package contains many useful methods such as killing a subprocess, making a thread wait for some time, returning the I/O stream of the subprocess etc.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec.htm
Java Runtime exec() Method
package com.tutorialspoint; public ... calc.exe Calculator should now open. The following example shows the usage of Java Runtime exec() method....
🌐
Oracle
docs.oracle.com › middleware › 11119 › jdev › api-reference-esdk › oracle › ide › runner › RunProcess.html
RunProcess (Oracle Fusion Middleware Java API Reference for Oracle Extension SDK Reference)
Tests whether this process can be started. ... Checks whether the Starter wants to bypass the RunProcess mode (run, debug, profile) and just launch the Starter. ... Checks whether this RunProcess can have contained RunProcess. ... public void start(Node node, AbstractStarterFactory abstractStarterFactory, java.lang.Object cookie)
🌐
GitHub
gist.github.com › padcom › a5831bea701ef08ce944
Running a process and reading its output in Java · GitHub
Running a process and reading its output in Java. GitHub Gist: instantly share code, notes, and snippets.
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
It describes the various pitfalls related to the Runtime.exec() method. This example will capture the output (from stdio) of an external program. package com.rgagnon.howto; import java.io.*; public class Exec { public static void main(String args[]) { try { String line; Process p = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } } } The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be interpreted by the shell.
🌐
PixelsTech
pixelstech.net › home › articles › launch java process programmatically in java
Launch Java process programmatically in Java | PixelsTech
April 27, 2016 - Once configured, calling ProcessBuilder.start() initiates the process, enabling developers to read its output, manage error streams, and retrieve the exit value upon completion. This approach provides robust control over external Java executions within an application.
🌐
GitHub
github.com › fleipold › jproc
GitHub - fleipold/jproc: Java library that helps with running external processes.
For more control over the execution we'll use a ProcBuilder instance to configure the process. The run method builds and spawns the actual process and blocks until the process exits.
Starred by 196 users
Forked by 23 users
Languages   Java 96.7% | Shell 3.3% | Java 96.7% | Shell 3.3%
🌐
Alvin Alexander
alvinalexander.com › java › edu › pj › pj010016
Running system commands in Java applications | alvinalexander.com
June 4, 2016 - Listing 1 (above): The file JavaRunCommand.java shows how you can run an external system command from within a Java program. The first thing you do is specify the command you want to run by supplying this command to the Runtime class. Because you can't create your own instance of the Runtime class, you first use the getRuntime method to access the current runtime environment and then invoke the Runtime exec method. This returns a Process object.
🌐
Medium
harith-sankalpa.medium.com › how-to-run-system-commands-from-java-applications-a914223edd24
How To Run System Commands From Java Applications | by Harith Sankalpa | Medium
October 21, 2019 - In Java, Runtime class cannot be instantiated explicitly. But you can obtain a Runtime object using, ... After obtaining a Runtime object, you can run a system command by either passing a complete system command with arguments as a one-string or an array of strings with the command and each argument as separate strings to the exec method. As soon as the “exec” method is called the input command will be run. exec() method returns a Process object which can be used for the next step.
🌐
Alvin Alexander
alvinalexander.com › java › java-exec-processbuilder-process-1
Java exec: Execute system processes with Java ProcessBuilder and Process (part 1) | alvinalexander.com
November 30, 2019 - To run that command from a Java application using my new code, we'd first build and then exec the command like this:
🌐
Jfeatures
jfeatures.com › blog › jps
Find all the Java processes running on your machine
May 28, 2021 - For rest of the blog post we will use jps on this process. java -XX:ConcGCThreads=6 -Xmx256m -Xms8m -Xss256k Test argument1 argument2
🌐
DEV Community
dev.to › dbillion › understanding-java-processes-53j0
Understanding Java Processes - DEV Community
May 5, 2024 - Creating a new process in Java is straightforward using the Runtime.exec() method or the ProcessBuilder class.