First, the 'cd' command can't be executed by Runtime.exec() in the first place (see How to use "cd" command using Java runtime?). You should be able to just set the working directory for the process when you call exec (see below).

Second, running 'cmd.exe /c' to execute your process isn't what you want here. You won't be able to get the results of your process running, because that is returned to the command window -- which eats the error and then closes without passing the error along to you.

Your exec command should look more like this:

CopyProcess p = Runtime.getRuntime().exec(
    command, null, "C:\Users\Eric\Documents\COSC\ecj");

Where 'command' looks like this:

CopyString command = "java ec.Evolve -file ec\app\tutorial5\tutorial5.params"

Edit: For reading error messages, try this:

CopyString error = "";
try (InputStream is = proc.getErrorStream()) {
    error = IOUtils.toString(is, "UTF-8");
}
int exit = proc.waitFor();
if (exit != 0) {
    System.out.println(error);
} else {
    System.out.println("Success!");
}
Answer from Dave on Stack Overflow
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec.htm
Java Runtime exec() Method
package com.tutorialspoint; public class RuntimeDemo { public static void main(String[] args) { try { // print a message System.out.println("Executing explorer.exe"); // create a process and execute explorer.exe Process process = Runtime.getRuntime().exec("explorer.exe"); // print another message System.out.println("Windows Explorer should now open."); } catch (Exception ex) { ex.printStackTrace(); } } }
Discussions

command - Java Runtime.exec() to run a java program - Stack Overflow
I prefer to use Apache's Commons Exec, it's provides an excellent facade over Java's Runtime.exec() and gives a nice way to specify the working directory. Another very nice thing is they provide utilities to capture standard out and standard err. More on stackoverflow.com
🌐 stackoverflow.com
Java Runtime.getRuntime(): getting output from executing a command line program - Stack Overflow
This is a character you would expect not to see. The default delimiter is whitespace, according to the Java documentation, so doing this would probably spit out the full result of the command. 2015-05-12T20:32:22.943Z+00:00 ... Runtime::exec(String cmd) is deprecated since Java 18. More on stackoverflow.com
🌐 stackoverflow.com
process - How to get java getRuntime().exec() to run a command-line program with arguments? - Stack Overflow
I have even tried passing "cmd ...\eurotext-example\"" and I ended up having the same error. According to Using Quotes within getRuntime().exec I thought problem was that I was that i had tried to escape the quotes, so that is why I passed in a String array. But I am still getting the Exited with error code 1. Is it possible to execute a command-line program with the java Runtime.getRuntim... More on stackoverflow.com
🌐 stackoverflow.com
Problem with Runtime.exec() method and using multiple commands in Linux
Appearently my problem was trying to use a shell command using .exec() which does run programs but cd is a shell not a executed/forked program. So I had to use this line on my runtime.exec() line: runtime.exec(new String[]{"/bin/sh", "-c", "cd /mnt/; ls --group-directories-first"}); More on reddit.com
🌐 r/javahelp
4
8
September 16, 2019
🌐
GitHub
gist.github.com › f3348e7843994bdd56f0
Java Runtime.getRuntime().exec() Example - Gist - GitHub
package api; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Exec { /** * @param args */ public static void main(String[] args) { String result = ""; try { // Execute command String command = "k:\\curl.exe -d login_name=mohwtest -d login_passwd=12345 --insecure https://mohw.cyberhood.net.tw/xml_import.php"; Process child = Runtime.getRuntime().exec(command); DataInputStream in = new DataInputStream( child.getInputStream()); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { result +=line; } in.close(); } catch (IOException e) { } System.out.println(result); } }
🌐
IBM
ibm.com › docs › en › i › 7.4.0
Calling another Java program with java.lang.Runtime.exec()
This example shows how to call another Java program with java.lang.Runtime.exec(). This class calls the Hello program that is shipped as part of the IBM Developer Kit for Java. When the Hello class writes to System.out, this program gets a handle to the stream and can read from it.
🌐
Java Guides
javaguides.net › 2023 › 09 › java-runtimeexec.html
Java Runtime.exec()
September 27, 2023 - - The subprocess is not synchronized with the Java application, so you might want to use methods like waitFor() on the Process object to have your Java program wait for the subprocess to finish. - Be cautious while executing arbitrary commands, especially if they are derived from untrusted sources. 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)
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Runtime.html
Runtime (Java Platform SE 7 )
Enable or disable finalization ... the Java runtime exits. By default, finalization on exit is disabled. If there is a security manager, its checkExit method is first called with 0 as its argument to ensure the exit is allowed. This could result in a SecurityException. ... SecurityException - if a security manager exists and its checkExit method doesn't allow the exit. ... Executes the specified ...
🌐
Tutorialspoint
tutorialspoint.com › java › lang › runtime_exec_dir.htm
Java.lang.Runtime.exec() Method
We've created a Process object for explorer executable using exec() method. This will invoke the windows explorer application. If some exception occurs, a corresponding stack trace is printed with error message. package com.tutorialspoint; import java.io.File; public class RuntimeDemo { public ...
Find elsewhere
🌐
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.
🌐
Java2s
java2s.com › example › java-api › java › lang › runtime › exec-3-0.html
Example usage for java.lang Runtime exec
From source file:org.openmrs.module.reportingsummary.api.io.util.InputOutputUtils.java · /** * Method to execute a command inside the shell. The command is usually the mysqldump or mysql command. * * @param commands the command array to be executed * @throws Exception when the task execution is interrupted *//* w ww .j av a 2s. c om*/ public static void executeCommand(final File workingDirectory, final String[] commands) throws Exception { Runtime runtime = Runtime.getRuntime(); Process process; if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) process = runtime.exec(commands, null, workingDi
🌐
Coderanch
coderanch.com › t › 419192 › java › Runtime-getRuntime-exec-String-command
Runtime getRuntime() exec(String command) - How does this work? (Java in General forum at Coderanch)
The key thing to remember when using Runtime.exec() is you must consume everything from the child process' input stream. [ June 16, 2003: Message edited by: Michael Morris ] Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher ... Well let me rephrase my question. How do you run an external windows command line program from a java ...
🌐
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
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;
}
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - For example, we can list all the directories inside the user’s home directory and then print it to the console: Process process; if (isWindows) { process = Runtime.getRuntime() .exec(String.format("cmd.exe /c dir %s", homeDirectory)); } else ...
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
package com.rgagnon.howto; import java.io.*; public class Exec { public static void main(String args[]) { try { String line; Process p = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } } } The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be interpreted by the shell.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-runtime-class-in-java
Java.lang.Runtime class in Java - GeeksforGeeks
May 6, 2022 - Example 2: Java · // Java Program ... try { // Creating a process and execute google-chrome Process process = Runtime.getRuntime().exec( "google-chrome"); System.out.println( "Google Chrome successfully started"); } // Catch ...
🌐
GitHub
gist.github.com › philipz › f3348e7843994bdd56f0
Java Runtime.getRuntime().exec() Example · GitHub
package api; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Exec { /** * @param args */ public static void main(String[] args) { String result = ""; try { // Execute command String command = "k:\\curl.exe -d login_name=mohwtest -d login_passwd=12345 --insecure https://mohw.cyberhood.net.tw/xml_import.php"; Process child = Runtime.getRuntime().exec(command); DataInputStream in = new DataInputStream( child.getInputStream()); BufferedReader br = new BufferedReader( new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { result +=line; } in.close(); } catch (IOException e) { } System.out.println(result); } }
🌐
More of Less
moreofless.co.uk › system-exec-java-not-working
How to exec external commands in Java with correct parameters
Process process = Runtime.getRuntime().exec("helloworld param1 param2"); int exitCode = process.waitFor(); System.out.println(exitCode); All good, now the problems start when we want to send a parameter of Mickey Mouse and to do that on the command line we'd put double-quotes around it to make ...
🌐
Code-white
code-white.com › blog › 2015-03-sh-or-getting-shell-environment-from
CODE WHITE | $@|sh – Or: Getting a shell environment from Runtime.exec
March 9, 2015 - We call this class as shown below with single quotes around the command line to ensure that our shell passes the command line argument to Java as is: ... Your first thought on a solution to this might be: “Ok, I’ll just use sh -c command to execute command in the shell.” · That is correct, but here is the catch: Since only the first argument following -c is interpreted as shell command, the whole shell command must be passed as a single argument. And if you take a closer look at how the string passed to Runtime.exec is processed, you’ll see that Java uses a StringTokenizer that splits the command at any white-space character.