Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

Answer from Senthil on Stack Overflow
Top answer
1 of 14
324

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

2 of 14
88

A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
🌐
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 · Raw · Execute.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › process_getoutputstream.htm
Java Process getOutputStream() Method
The Java Process getOutputStream() method gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - But for now, you need to add a few lines of code to grab the program’s output and print it: // part of ExecDemoLs.java p = Runtime.getRuntime( ).exec(PROGRAM); // getInputStream gives an Input stream connected to // the process p's standard output (and vice versa).
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
Leo3418
leo3418.github.io › 2021 › 06 › 20 › java-processbuilder-stdout.html
Properly Handling Process Output When Using Java’s ProcessBuilder - Leo3418's Personal Site
After I was almost determined to unravel this issue’s root cause, I started java-ebuilder in a new environment and left it running, as an attempt to both reproduce the hanging behavior and see if it could eventually get rid of the stasis if it was given hours of time, then left my computer for a break. When I returned after about 10 minutes, I saw something that was never shown before: Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited at java.lang.UNIXProcess.exitValue(UNIXProcess.java:421) at org.gentoo.java.ebuilder.maven.MavenParser.getEffectivePom(Ma
Top answer
1 of 5
70

Use getErrorStream().

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

EDIT:

You can use ProcessBuilder (and also read the documentation)

ProcessBuilder   ps=new ProcessBuilder("java.exe","-version");

//From the DOC:  Initially, this property is false, meaning that the 
//standard output and error output of a subprocess are sent to two 
//separate streams
ps.redirectErrorStream(true);

Process pr = ps.start();  

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
pr.waitFor();
System.out.println("ok!");

in.close();
System.exit(0);
2 of 5
11

Note that we're reading the process output line by line into our StringBuilder. Due to the try-with-resources statement we don't need to close the stream manually. The ProcessBuilder class let's us submit the program name and the number of arguments to its constructor.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessOutputExample
{
    public static void main(String[] arguments) throws IOException,
            InterruptedException
    {
        System.out.println(getProcessOutput());
    }

    public static String getProcessOutput() throws IOException, InterruptedException
    {
        ProcessBuilder processBuilder = new ProcessBuilder("java",
                "-version");

        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        StringBuilder processOutput = new StringBuilder();

        try (BufferedReader processOutputReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));)
        {
            String readLine;

            while ((readLine = processOutputReader.readLine()) != null)
            {
                processOutput.append(readLine + System.lineSeparator());
            }

            process.waitFor();
        }

        return processOutput.toString().trim();
    }
}

Prints:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
🌐
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 Process API: @Test public void whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException { Process process = Runtime.getRuntime() .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java"); process = Runtime.getRuntime() .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample"); BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream())); int value = Integer.parseInt(output.readLine()); assertEquals(3, value); }
Find elsewhere
Top answer
1 of 2
4

You don't want that call to waitFor() since it waits until the process is destroyed. You also don't want to read for as long as the InputStream is open, since such a read would terminate only when the process is killed.

Instead, you can simply start the process, and then wait for 7 seconds. Once 7 seconds have passed, read the available data in the buffer without waiting for the stream to close:

CopyBufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
Thread.sleep(7000); //Sleep for 7 seconds
while (stdInput.ready()) { //While there's something in the buffer
     //read & print - replace with a buffered read (into an array) if the output doesn't contain CR/LF
    System.out.println(stdInput.readLine()); 
}
p.destroy(); //The buffer is now empty, kill the process.

If the process keeps printing, so stdInput.ready() always returns true you can try something like this:

CopyBufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[16 * 1024]; // 16 KiB buffer, change size if needed
long startedReadingAt = System.currentTimeMillis(); //When did we start reading?
while (System.currentTimeMillis() - startedReadingAt < 7000) { //While we're waiting
    if (stdInput.ready()){
        int charsRead = stdInput.read(buffer); //read into the buffer - don't use readLine() so we don't wait for a CR/LF
        System.out.println(new String(buffer, 0, charsRead));  //print the content we've read
    } else {
        Thread.sleep(100); // Wait for a while before we try again
    }
}
p.destroy(); //Kill the process

In this solution, instead of sleeping, the thread spends the next 7 seconds reading from the InputStream, then it closes the process.

2 of 2
0

java.io.IOException: Stream closed That is probably because you're calling temp.readLine() after p.destroy().

The problem seems to be that the process doesn't add a new line termination after the part that you want to retrieve. To fix that, you can read the output from the program in small chunks instead of line by line.

Here is an example:

Copytry(InputStream is = p.getInputStream()){
    byte[] buffer = new byte[10];
    String content = "";
    for(int r = 0; (r = is.read(buffer))!=-1;){
        content+=new String(buffer, 0, r);
        if(content.equals("all content")){// check if all the necessary data was retrieved.
            p.destroy();
            break;
        }
    }
}catch(Exception e){
    e.printStackTrace();
}

If you know the exact format of the program's output, a better solution will be to use a scanner.

Copytry(Scanner sc = new Scanner(p.getInputStream())){
    while(sc.hasNext()){
        String word = sc.next();
    }
}catch(Exception e){
    e.printStackTrace();
}

The example above will read the program's output one word at a time.

From your comments it seems that the problem is that the process never terminates by itself and your program never exits the while loop.

To fix that, you can use a timer to destroy the process after a period of time, here is an example:

CopyTimer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
        p.destroy();
        t.cancel();
        t.purge();
    }
}, 7000);

try(BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));){
    while ((inputRead=stdInput.readLine()) != null){
        ...
    }
}catch(Exception e){
    e.printStackTrace();
}

Keep in mind that this approach will always cause stdInput.readLine() to throw an exception.

Top answer
1 of 2
10

Because the Process will execute in a new thread it's likely that there is no output or incomplete output available when you come to your while loop.

Process p = pb.start();  
// process runs in another thread parallel to this one

BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));

// bri may be empty or incomplete.
while ((line = bri.readLine()) != null) {
    RESULT+=line;
}

So you need to wait for the process to complete before attempting to interact with it's output. Try using the Process.waitFor() method to pause the current thread until your process has had an opportunity to complete.

Process p = pb.start();  
p.waitFor();  // wait for process to finish then continue.

BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = bri.readLine()) != null) {
    RESULT+=line;
}

This is only a simple approach you could also process the output of the process while it runs in parallel but then you would need to monitor the status of the process i.e. is it still running or has it completed, and the availability of output.

2 of 2
7

Use Apache Commons Exec, it will make your life much easier. Check the tutorials for information about basic usage. To read the command line output after obtaining an executor object (probably DefaultExecutor), create an OutputStream to whatever stream you wish (i.e a FileOutputStream instance may be, or System.out), and:

executor.setStreamHandler(new PumpStreamHandler(yourOutputStream));
🌐
ZetCode
zetcode.com › java › processbuilder
Java ProcessBuilder - creating processes in Java
May 1, 2025 - With the getInputStream method we get the input stream from the standard output of the process. $ java Main.java Február 2022 Ne Po Ut St Št Pi So 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - The Tabnine Code Library is no longer available — but you can still get the answers and suggestions you need from our AI code assistant.
🌐
Quora
quora.com › How-can-I-capture-console-output-from-another-Java-process
How to capture console output from another Java process - Quora
Things to consider: - Getting the order of operations right is essential. A pipe should be opened for reading first before another process opens for writing. IIRC. - If Java doesn't seem to be reading anything, your process might not be flushing output when you expec
🌐
Coderanch
coderanch.com › t › 672077 › java › read-output-Runtime-getRuntime-exec
Trying to read the output of a Runtime.getRuntime().exec cmd process. (Java in General forum at Coderanch)
October 27, 2016 - I'm using the below code and the connection establishes fine but I can't see any output redirecting to java. I can see the output from the cmd box. Any assistance would be appreciated. Thanks. ... I can see the output from the cmd box. What happens if you call the rasdial command and not the cmd command? ... That looks too complicated for us who are only beginning so I shall move you. Have you read the classic article by Michael Daconta? Don't go anywhere near Runtime.exec() until you have. If you use the old‑fashioned way to run Processes, rather than combining streams with a ProcessBuilder, you need two additional threads.