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();
      }
   }

}
🌐
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\"");
🌐
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(); } } }
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.
🌐
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.
🌐
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.
🌐
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 =
🌐
Tabnine
tabnine.com › home › code library
https://www.tabnine.com/code/java/methods/java.lan...
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
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 ...
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
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
🌐
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.
🌐
javaspring
javaspring.net › blog › java-runtime-exec
Java Runtime Exec: A Comprehensive Guide — javaspring.net
It's important to read the standard error stream of the process to handle any errors that may occur during the execution of the command. Here is an example that reads both the standard output and standard error: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadErrorStreamExample { public static void main(String[] args) { try { String command = "ls non_existent_directory"; Process process = Runtime.getRuntime().exec(command); // Read standard output BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInpu
🌐
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...