You need to read the output (and error) streams from the Process using getInputStream() and getErrorStream(). You’ll need a separate thread for this if you want to wait for the process to complete.

String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
final InputStream pOut = p.getInputStream();
Thread outputDrainer = new Thread()
{
    public void run()
    {
        try
        {
            int c;
            do
            {
                c = pOut.read();
                if (c >= 0)
                    System.out.print((char)c);
            }
            while (c >= 0);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
};
outputDrainer.start();

p.waitFor();

If you are using Java 7 and want all output of the process to be redirected to the console, the code is considerably simpler:

String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectError(Redirect.INHERIT)
                                   .redirectOutput(Redirect.INHERIT)
                                   .start();
p.waitFor();

The redirectError() and redirectOutput() methods with Redirect.INHERIT cause output to just be sent to the parent Java process.

Answer from prunge 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;
}
Discussions

java - Eclipse gives different output than cmd using runtime exec - Stack Overflow
You have different system environment ... and executing from Eclipse. Variables of environment are valuable : PATH, JAVA_HOME or JRE_HOME and your current worikng directory. I use ProcessBuilder in cases, when I must be sure in environment, that is provided for external process like yours "java ... More on stackoverflow.com
🌐 stackoverflow.com
python - Runtime.getRuntime().exec() won't work in Java Eclipse - Stack Overflow
My console always reads null and ... and I get the correct output: C:\users\user\workspace\project>python pythonscript.pyw · Does this have something to do with specifying my directory in Eclipse? ... Yes, most likely. Make sure python is found by exec. (Related question: stackoverflow.com/questions/9368666/…) ... Your Java file and ... More on stackoverflow.com
🌐 stackoverflow.com
June 8, 2015
java - Capturing stdout when calling Runtime.exec - Stack Overflow
When experiencing networking problems on client machines, I'd like to be able to run a few command lines and email the results of them to myself. I've found Runtime.exec will allow me to execute More on stackoverflow.com
🌐 stackoverflow.com
How to capture output of java files using Runtime.exec
Hi guys, I'm trying to capture output of java files using Runtime.exec but I don't know how. More on community.oracle.com
🌐 community.oracle.com
July 17, 2006
🌐
Stack Overflow
stackoverflow.com › questions › 12218138 › how-to-run-an-exe-and-capture-the-output-in-an-eclipse-plugin-java
How to run an .exe and capture the output in an Eclipse Plugin. (Java) - Stack Overflow
Process p = Runtime.getRuntime().exec("executable.exec"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((String line = input.readLine()) != null) { System.out.println(line); }
Top answer
1 of 2
2

You have different system environment in executing from command string and executing from Eclipse.

Variables of environment are valuable : PATH, JAVA_HOME or JRE_HOME and your current worikng directory.

I use ProcessBuilder in cases, when I must be sure in environment, that is provided for external process like yours "java CPU/memory".

I think that first of all your external process have wrong working directory. In ProcessBuilder you can point on it with:

ProcessBuilder pb = new ProcessBuilder("java", "CPU/MEMORY");   
pb.directory(new File("/home/myhome/myjavaprojects"));
Process p = pb.start();
2 of 2
0

Don't ignore the ErrorStream. If you read it (in its own thread), you'll see what you're doing wrong.

For example:

import java.io.*;

public class Foo001 {
   public static void main(String[] args) {
      System.out.println("hellow");
      try {
         int x;
         Runtime rt = Runtime.getRuntime();
         Process proc = rt.exec("java CPU/memory");
         final BufferedReader in = new BufferedReader(new InputStreamReader(
               proc.getInputStream()));
         final BufferedReader err = new BufferedReader(new InputStreamReader(
               proc.getErrorStream()));
         new Thread(new ReadLiner(in, "in")).start();
         new Thread(new ReadLiner(err, "err")).start();
         // proc.waitFor(); // not sure that this is needed
      } catch (Throwable t) {
         t.printStackTrace();
      }
   }
}

class ReadLiner implements Runnable {
   private BufferedReader br;
   private String text;

   public ReadLiner(BufferedReader br, String text) {
      this.br = br;
      this.text = text;
   }

   @Override
   public void run() {
      String line = null;
      try {
         while ((line = br.readLine()) != null) {
            System.out.println(text + ": " + line);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

}
🌐
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.
🌐
Stack Overflow
stackoverflow.com › questions › 30704232 › runtime-getruntime-exec-wont-work-in-java-eclipse
python - Runtime.getRuntime().exec() won't work in Java Eclipse - Stack Overflow
June 8, 2015 - if you can try this outside of eclipse ,you can check is it work .make sure .class file and .pyw lying inside same folder · – Madhawa Priyashantha Commented Jun 8, 2015 at 8:36 ... You shuld put your pyw script to working directory of running java application. ... String scriptDir = "./some dir"; Process p = Runtime.getRuntime().exec("cmd /c \"cd " + scriptDir + " && python pythonscript.pyw\"");
Find elsewhere
🌐
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.
🌐
Oracle Community
community.oracle.com › groundbreakers developer community › java programming
How to capture output of java files using Runtime.exec — oracle-tech
July 17, 2006 - Hi guys, I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to · import java.io.*; public class CmdExec { public CmdExec() { } public static void main(String argv[]){ try { String line; Runtime rt = Runtime.getRuntime(); String[] cmd = new String[2]; cmd[0] = "javac"; cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java"; Process proc = rt.exec(cmd); cmd = new String[2]; cmd[0] = "javac"; cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E"; proc =
🌐
Coderanch
coderanch.com › t › 40 › 419192 › java › Runtime-getRuntime-exec-String-command
Runtime getRuntime() exec(String command) - How does this work? (Java in General forum at Coderanch)
Write to the process' output stream. You can wrap that in a PrintStream if you want. SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... I want to execute a command in my java program using below function. Process p = Runtime.getRuntime().exec(); My command om cmd prompt looks something like C:\Program Files\IBM\MQSI\9.0.0.0>mqsicacheadmin IB9NODE -c clearGrid -m myMapName Please do tell correct format of writing above command inside exec() block am getting some error when tried.
🌐
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
🌐
Oracle
forums.oracle.com › ords › apexds › post › how-to-capture-output-of-java-files-using-runtime-exec-4037
How to capture output of java files using Runtime.exec - Oracle Forums
July 17, 2006 - Hi guys, I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :( imp...
🌐
Java Guides
javaguides.net › 2023 › 09 › java-runtimeexec.html
Java Runtime.exec()
September 27, 2023 - public class ExecuteCommandExample { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); try { // Using the first syntax: exec(String command) Process process = runtime.exec("ping -c 1 www.google.com"); // Retrieving the input stream (where the command sends its output) BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // Wait for the process to exit and get the return value int exitValue = process.waitFor(); System.out.println("Process exit value: " + exitValue); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
🌐
Coderanch
coderanch.com › t › 425969 › java › output-Runtime-getRuntime-exec
Help for getting output of Runtime.getRuntime().exec() (Java in General forum at Coderanch)
Runtime.getRuntime().exec("cmd/c start C:/jdk1.4/BIN/javac filename.java"); . My code is like this Anyone can help me please.
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)
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - With it, you can instruct the OS to perform tasks outside the realm of Java, seamlessly integrating your application with the underlying system. So let's get into the details. Before we jump into the practical examples, let's cover some essential concepts related to the exec() method: Runtime Object: The exec() method belongs to the Runtime class, which represents the runtime environment of the application.
🌐
Reddit
reddit.com › r/javahelp › java runtime exec not outputting what i expect
r/javahelp on Reddit: Java Runtime Exec not outputting what I expect
June 3, 2016 - ... You might have to do "cmd javac" Look at how to do Java exec for "cd" where they explain why it won't work ... I'm on a Linux computer. Runtime.getRuntime().exec("ls -l") just works as is.