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);
Answer from KV Prajapati on Stack Overflow
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)
🌐
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.
🌐
Leo3418
leo3418.github.io › 2021 › 06 › 20 › java-processbuilder-stdout.html
Properly Handling Process Output When Using Java’s ProcessBuilder - Leo3418's Personal Site
The write methods of OutputStream allow the Java program to write data to the pipe whose output end is connected to the Unix process. Similarly, the read methods of InputStream enable the Java program to read data from the pipe whose input end is connected to the Unix process.
🌐
DaniWeb
daniweb.com › programming › software-development › tutorials › 536301 › how-to-read-stdout-from-an-external-process-in-java-17
How to read stdout from an external process in Java 17
September 23, 2021 - Although not included in the headlines, the release of JDK 17 also added 3 sets of new methods to the class java.lang.Process: ... In this tutorial, we are going to learn how to use Process.inputReader() to read stdout from external processes.
🌐
Chenjianjx
chenjianjx.com › read-process-output-in-java-without-hanging-the-main-thread
Read process output in Java without hanging the main thread – CHEN Jian's Java Blog
November 11, 2019 - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.jaxws.util.io.StreamPrinter; /** * Spawning a process from the OS * * @author chenjianjx * */ public class SystemProcessUtils { /** * execture a program and returns console output */ public static String exec(String[] cmdArray) throws SystemProcessException { try { Process p = Runtime.getRuntime().exec(cmdArray); ByteArrayOutputStream output = new ByteArrayOutputStream(); Thread errStreamThread = collectErrorStream(p, output); Thread inputStreamThread = collectInputStream(p, output); int r
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - Content preview from Java Cookbook · You want to run a program but also capture its output. Use the Process object’s getInputStream( ) ; read and copy the contents to System.out or wherever you want them. A program’s standard and error output does not automatically appear anywhere.
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
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.
🌐
Stack Overflow
stackoverflow.com › questions › 30210481 › java-read-the-output-of-a-process
Java - Read the output of a process - Stack Overflow
Process core = pb.start(); if(!core.waitFor(3, TimeUnit.HOURS)) { System.out.println("Process destroyed, path " + root.getAbsolutePath()); core.destroy(); } String output = IOUtils.toString(core.getInputStream()); return output;
Find elsewhere
🌐
Medium
medium.com › enekochan › run-a-command-from-a-java-application-dealing-properly-with-stdin-stdout-and-stderr-8be78063f2cf
Run a command from a Java application dealing properly with stdin, stdout and stderr | by Eneko | enekochan | Medium
November 5, 2018 - The key is to read the output and error buffers. This is a simple example on how to do this: import java.io.*; public class CmdExec { public static void main(String argv[]) { try { String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; // launch the command and grab stdin/stdout and stderr Process process = Runtime.getRuntime().exec("ls -la"); stdin = process.getOutputStream(); stderr = process.getErrorStream(); stdout = process.getInputStream(); // You could write to sdtin too but it's useless for the ls we are doing ;) line = "param1" + "n"; stdin.write
🌐
Coderanch
coderanch.com › t › 367999 › java › Reading-output-System-exec-Process
Reading output from a System.exec Process (Java in General forum at Coderanch)
Here is the sample code <pre> import java.io.*; public class ls { public static void main(String a[]) { try{ Process p = Runtime.getRuntime().exec(ls); DataInputStream dis = new DataInputStream(p.getInputStream()); String line = ""; while ( (line = dis.readLine()) != null) { System.out.println(line); } dis.close(); }catch(Exception e) { e.printStackTrace(); } } } </pre> [This message has been edited by Aleksey Matiychenko (edited July 06, 2001).]
🌐
Stack Overflow
stackoverflow.com › questions › 28971577 › capture-output-of-a-running-process-in-java
capture output of a running process in Java - Stack Overflow
(I'm using Windows 7) I know how to start a process, pass some arguments and read the output of that process. import java.io.*; class Test { public static void main(String args[]) throws IOException { ProcessBuilder pb = new ProcessBuilder("java", "ProgramFoo", "ArgBar"); Process process = pb.start(); final InputStream is = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Process.html
Process (Java Platform SE 8 )
April 21, 2026 - 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.
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;
}
🌐
Stack Overflow
stackoverflow.com › questions › 40338198 › how-to-read-output-from-command-com-in-java
process - How to read output from command.com in java - Stack Overflow
November 1, 2016 - Process p=Runtime.getRuntime().exec("command /c echo goodbye world"); //command.com doesn't work eiher p.waitFor(); BufferedReader reader=new BufferedReader( new InputStreamReader(p.getInputStream()) ); String line=""; String output=""; while((line = reader.readLine()) != null) { output+=line; } System.out.print(line);
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));