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
🌐
Baeldung
baeldung.com › home › java › core java › guide to java.lang.process api
Guide to java.lang.Process API | Baeldung
June 10, 2025 - We can see from the above example that for the current thread to continue execution, it will keep on waiting for the subprocess thread to end, or if the specified time interval has elapsed. When this method is executed, it will return a boolean value of true if the subprocess has exited or a boolean value of false if the wait time has elapsed before the subprocess exited. IllegalMonitorStateException: Current thread is not owner of the lock! in Java’s java.lang.Process API usually arises when attempting to use methods like wait() or notify() on a Process object without properly acquiring its monitor lock.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-process-class-java
Java.lang.Process class in Java - GeeksforGeeks
February 15, 2023 - Process(): This is the only constructor. ... Syntax: public abstract void destroyForcibly(). Returns: NA. Exception: NA. ... // Java code illustrating destroyForcibly() // method for windows operating system // Class public class ProcessDemo ...
🌐
Happy Coding
happycoding.io › tutorials › java › processing-in-java
Processing in Java - Happy Coding
May 6, 2017 - For example, in the Swing tutorial we extended the JPanel class and overrided the paintComponent() function to perform custom painting. When using Processing as a Java library, we want to do something similar: we’ve extended the PApplet class, and now we want to override various functions to change their behavior- these are the Processing functions you’re used to, like draw() and mousePressed().
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>
🌐
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.
🌐
DEV Community
dev.to › sadiul_hakim › java-process-api-basics-aml
Java Process API Basics - DEV Community
September 24, 2025 - Creating a graphical user interface (GUI) for a command-line tool: Your Java GUI can launch and interact with a command-line tool, displaying its output and providing user input. Parallel processing: You can offload a computationally intensive ...
🌐
Ongres
ongres.com › blog › java-processes-and-streams
OnGres | Java, Processes and Streams
November 24, 2020 - Finally, if you are on Java 1.8+ and want to benefit of the new Java APIs, you need a lightweight approach or you simply want simpler code, Fluent Process is here to help be more productive allowing yuo to write less and do stuffs faster. Fluent Process is open source created at OnGres. If you like it, please star it and share the project! You can find the source code of this blog post code examples here: https://gitlab.com/ongresinc/blog-posts-src/-/tree/master/20200820-java_process_and_streams/examples
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › java › lang › java_lang_process.htm
Java Process Class
package com.tutorialspoint; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process..."); Process p = Runtime.getRuntime().exec("notepad.exe"); // wait 10 seconds ...
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › lang › Process.html
Process (Java SE 9 & JDK 9 )
For example, to delegate to the underlying process, it can do the following: public CompletableFuture<Process> onExit() { return delegate.onExit().thenApply(p -> this); } ... Returns a ProcessHandle for the Process. Process objects returned by ProcessBuilder.start() and Runtime.exec(java.l...
🌐
DEV Community
dev.to › dbillion › understanding-java-processes-53j0
Understanding Java Processes - DEV Community
May 5, 2024 - For example, when dealing with multiple processes, you must ensure that shared resources are accessed in a thread-safe manner to avoid race conditions. Here’s a more complex snippet that demonstrates handling multiple processes and their streams concurrently: import java.io.*; import java.util.concurrent.*; public class MultiProcessHandler { private static final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); public static void handleProcess(Process process) { // Handle output stream executor.submit(() -> { try (BufferedReader reader = new
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › core › creating-process.html
Creating a Process
October 20, 2025 - public static void setEnvTest() throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "echo $horse $dog $HOME").inheritIO(); pb.environment().put("horse", "oats"); pb.environment().put("dog", "treats"); pb.start().waitFor(); }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-processbuilder-class-java
Java.lang.ProcessBuilder class in Java - GeeksforGeeks
January 14, 2022 - Key = PATH, Value = /usr/bin:/bin:/usr/sbin:/sbin Key = JAVA_MAIN_CLASS_14267, Value = ProcessBuilderDemo Key = J2D_PIXMAPS, Value = shared Key = SHELL, Value = /bin/bash Key = JAVA_MAIN_CLASS_11858, Value = org.netbeans.Main Key = USER, Value = abhishekverma Key = TMPDIR, Value = /var/folders/9z/p63ysmfd797clc0468vvy4980000gn/T/ Key = SSH_AUTH_SOCK, Value = /private/tmp/com.apple.launchd.uWvCfYQWBP/Listeners Key = XPC_FLAGS, Value = 0x0 Key = LD_LIBRARY_PATH, Value = /Library/Java/JavaVirtualMachines /jdk1.8.0_121.jdk/Contents/Home/jre/lib/ amd64:/Library/Java/JavaVirtualMachines/jdk1.8.0_121
🌐
IBM
ibm.com › docs › en › i › 7.4.0
IBM i
October 7, 2025 - Note: By using the code examples, you agree to the terms of the Code license and disclaimer information. import java.io.*; public class CallHelloPgm { public static void main(String args[]) { Process theProcess = null; BufferedReader inStream = null; System.out.println("CallHelloPgm.main() invoked"); // call the Hello class try { theProcess = Runtime.getRuntime().exec("java QIBMHello"); } catch(IOException e) { System.err.println("Error on exec() method"); e.printStackTrace(); } // read from the called program's standard output stream try { inStream = new BufferedReader( new InputStreamReader( theProcess.getInputStream() )); System.out.println(inStream.readLine()); } catch(IOException e) { System.err.println("Error on inStream.readLine()"); e.printStackTrace(); } } } Copy to clipboard ·
🌐
Infinite-erp
wiki.infinite-erp.co.id › index.php › How_to_create_a_Java_Process
How to create a Java Process - InfiniteERP Wiki
Let's explain it using a little example (this class and its parameters are used in the process definition further down in this howto): <source lang="java">public class ExampleJavaProcess extends DalBaseProcess {
🌐
Tutorialspoint
tutorialspoint.com › home › java › java process api improvements
Java Process API Improvements
February 13, 2026 - Process ID : 5352 Command name : C:\Program Files\Java\jdk-21\bin\javaw.exe Command line : Not Present Start time: 2024-04-02T17:09:17.902 Arguments : Not Present User : DESKTOP-DTHL8BI\Tutorialspoint · In this example, we've getting current process chid processes using ProcessHandle.current().children() method.
🌐
Coderanch
coderanch.com › t › 708675 › engineering › Monitor-System-Processes-Java
How to Monitor System Processes in Java (General Computing forum at Coderanch)
Tim Moores wrote:I see, what you're asking is how to obtain the CPU and memory usage info for a chosen process. I'm not a Windows expert, but this discussion has a number of starting points on how to do that. Discussion is from 2008. Perfmon.exe is still available in Win-10 but is a GUI with no API as far as I can tell. They also mention WMI which doesn't run on Win-10. You'll need something with an API or at least log files. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
DEV Community
dev.to › harithay › introduction-to-java-processhandle-5950
Introduction to Java ProcessHandle - DEV Community
September 16, 2024 - This is a quick introduction to application of Java ProcessHandle through a use case. ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java.lang.processbuilder api
Guide to java.lang.ProcessBuilder API | Baeldung
November 26, 2025 - 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:
🌐
Dot Net Perls
dotnetperls.com › process-java
Java - Process, ProcessBuilder Examples - Dot Net Perls
September 16, 2024 - Note 2 Sometimes a specific browser ... class Program { public static void main(String[] args) throws IOException { ProcessBuilder b = new ProcessBuilder(); // Create an ArrayList with two values....