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.

Answer from jsuhre on Stack Overflow
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));
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - // 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). We use // that to construct a BufferedReader so we can readLine( ) it.
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
Stack Overflow
stackoverflow.com › questions › 52389986 › java-execute-an-external-program-and-capture-the-output
command line - Java Execute an external program and capture the output - Stack Overflow
September 18, 2018 - So i try to Execute an external program and capture the output. Currently the part that execute command works fine (using .bat file) and i can see the output on the cmd window. The part that need to read the output not and it seemt that it stack inside my while ... String[] command = {"cmd.exe", "/C", "Start", "d:\\batFile.bat"}; Process process = Runtime.getRuntime().exec(command); InputStream is = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); }
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; // launch EXE and grab stdin/stdout and stderr Process process = Runtime.getRuntime ().exec ("/folder/exec.exe"); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the parms into stdin line = "param1" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param2" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param3" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); stdin.close(); // clean up if any output i
🌐
CodingTechRoom
codingtechroom.com › question › run-external-program-in-java
How to Execute an External Program in Java, Capture Output, and Enable Interruption? - CodingTechRoom
... ProcessBuilder processBuilder = new ProcessBuilder("your-command-here"); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); Running external programs in Java involves using the `ProcessBuilder` class, allowing you to start system processes, capture their ...
🌐
Real's HowTo
rgagnon.com › javadetails › java-0648.html
Launch an external program, capture its output and display it in a JSP - Real's Java How-to
The JSP captures the output and to display it as Web page. <H1>Members of the <%=request.getParameter("group")%> group</H1> <% String cmdline = "net group " + request.getParameter("group") + " /domain"; out.println("<pre>"); try { String line; ...
🌐
Ispycode
ispycode.com › Blog › java › 2017-04 › Capture-output-from-external-program
Capture output from external program | java blog - I Spy Code
Here is a java example that captures the output of an external program: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Example { public static void main(String[] args) throws IOException { String command = "ls /var"; String output = runCommand(command); System.out.println(output); } public static String runCommand(String command){ String output = ""; String line; try { Process p = Runtime.getRuntime().exec(command); try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) { while ((line = input.readLine()) != null) { output = output + line + '\n'; } } } catch (IOException ex) { System.out.println(ex.getMessage()); } return output; } }
🌐
Java-tips
java-tips.org › home › java se tips › java.io › how to capture the output of an external program
How to capture the output of an external program - Java Tips
How to capture the output of an external program · Print · You can capture the output of an external program using the logic shown below: [myprog.bat] echo hello world!
Find elsewhere
🌐
GitHub
github.com › fleipold › jproc
GitHub - fleipold/jproc: Java library that helps with running external processes.
For the basic use case of just capturing program output there is a static method: String output = ProcBuilder.run("echo", "Hello World!"); assertEquals("Hello World!\n", output); There is another static method that filters a given string through ...
Starred by 196 users
Forked by 23 users
Languages   Java 96.7% | Shell 3.3% | Java 96.7% | Shell 3.3%
🌐
Baeldung
baeldung.com › home › java › core java › execute a jar file from a java program
Execute a JAR File From a Java Program | Baeldung
February 7, 2025 - The getClass().getClassLoader().getResource(RUNNABLE_JAR_PATH) method gets the resource URL, which we’re ensuring is not null and converting into a URI. We then set up a command using java -jar, a standard way to execute an executable JAR. Next, we’re using ProcessBuilder to execute the JAR as a new process. Once the execution is started, we try to capture the program output from the input stream.
🌐
Quora
quora.com › How-can-I-capture-console-output-from-another-Java-process
How to capture console output from another Java process - Quora
Answer: Spawn a child process and redirect stdin and stdout to streams your process uses. For example, * Create a pipe “stdin” * Create a pipe “stdout” * Specify the output side of the stdin pipe to the stdin port of the child process * Specify the input side of the stdout pipe to the ...
🌐
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); } } }
Top answer
1 of 2
4

I'm assuming you're invoking the other program through either ProcessBuilder or Runtime.exec() both return a Process object which has methods getInputStream() and getErrorStream() which allow you to listen on the output and error (stdout, stderr) streams of the other process.

Consider the following code:

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

public class Test {

    public static void main(String[] args){
        Test t = new Test();

        t.start();
    }

    private void start(){
        String command = //Command to invoke the program

        ProcessBuilder pb = new ProcessBuilder(command);

        try{
            Process p = pb.start();

            InputStream stdout = p.getInputStream();
            InputStream stderr = p.getErrorStream();

            StreamListener stdoutReader = new StreamListener(stdout);
            StreamListener stderrReader = new StreamListener(stderr);

            Thread t_stdoutReader = new Thread(stdoutReader);
            Thread t_stderrReader = new Thread(stderrReader);

            t_stdoutReader.start();
            t_stderrReader.start();
        }catch(IOException n){
            System.err.println("I/O Exception: " + n.getLocalizedMessage());
        }
    }

    private class StreamListener implements Runnable{
        private BufferedReader Reader;
        private boolean Run;

        public StreamListener(InputStream s){
            Reader = new BufferedReader(new InputStreamReader(s));
            Run = true;
        }

        public void run(){
            String line;

            try{
                while(Run && (line = Reader.readLine()) != null){
                    //At this point, a line of the output from the external process has been grabbed. Process it however you want.
                    System.out.println("External Process: " + line);
                }
            }catch(IOException n){
                System.err.println("StreamListener I/O Exception!");
            }
        }
    }
}
2 of 2
0

grasp this example:

  // Try these charsets for encoding text file
  String[] csStrs = {"UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16", "GB2312", "GBK", "BIG5"};
  String outFileExt = "-out.txt";   // Output filenames are "charset-out.txt"

  // Write text file in the specified file encoding charset
  for (int i = 0; i < csStrs.length; ++i) {
     try (OutputStreamWriter out =
             new OutputStreamWriter(
                new FileOutputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedWriter bufOut = new BufferedWriter(out)) {  // Buffered for efficiency
        System.out.println(out.getEncoding());  // Print file encoding charset
        bufOut.write(message);
        bufOut.flush();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read raw bytes from various encoded files
  //   to check how the characters were encoded.
  for (int i = 0; i < csStrs.length; ++i) {
     try (BufferedInputStream in = new BufferedInputStream(  // Buffered for efficiency
             new FileInputStream(csStrs[i] + outFileExt))) {
        System.out.printf("%10s", csStrs[i]);    // Print file encoding charset
        int inByte;
        while ((inByte = in.read()) != -1) {
           System.out.printf("%02X ", inByte);   // Print Hex codes
        }
        System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read text file with character-stream specifying its encoding.
  // The char will be translated from its file encoding charset to
  //   Java internal UCS-2.
  for (int i = 0; i < csStrs.length; ++i) {
     try (InputStreamReader in =
             new InputStreamReader(
                new FileInputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedReader bufIn = new BufferedReader(in)) {  // Buffered for efficiency
        System.out.println(in.getEncoding());  // print file encoding charset
        int inChar;
        int count = 0;
        while ((inChar = in.read()) != -1) {
           ++count;
           System.out.printf("[%d]'%c'(%04X) ", count, (char)inChar, inChar);
        }
     System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

} }

🌐
Javachannel
javachannel.org › posts › external-program-invocation-in-java
External Program Invocation in Java – Libera #java
February 26, 2016 - It runs, but may block on some operations – consider yourself warned, prepare to hit ^C, and use it as a point of emphasis on why you should be using zt-exec, shown immediately below… ... import org.zeroturnaround.exec.ProcessExecutor; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Example2 { public static void main(String[] args) throws InterruptedException, TimeoutException, IOException { String output = new ProcessExecutor() .command("echo", "Hello World") .readOutput(true) .execute() .outputUTF8(); System.out.println(output); } }
🌐
Archlinux
copyprogramming.com › t › java-execute-an-external-program-and-capture-the-output
Java Execute An External Program And Capture The Output - CopyProgramming
JAR file that executes all the test from cmd.exe and i want to automate this with a java script, , so I can run it and read the output., jar file uses a few arguments to execute, like this: -java jar, which is you're in doubt about as I understand) There is some external, Question: When i execute my java application ... Solution 1: The best practice is to import the two programs, in a 3rd one like import pass import rockpaper which will execute, rocke} {papery} But I am a scissors") if __name__ == "__main__": sharp() Output, h4> modB.py: import modA print(modA.addiction(2,3)) output, of modA.py import modA.py print "some ModB.py stuff here" #second execution of modA.py imp.reload(modA.py
🌐
Coder Scratchpad
coderscratchpad.com › home › java: how to run system commands and capture output
Java: How to Run System Commands and Capture Output
October 17, 2025 - Whether you're a tech newbie or a total pro, get the skills and confidence to land your next move. Start 10-Day Free Trial · Following code shows how to use the ProcessBuilder class to execute an external system command and capture the output.