You are not capturing STDERR, so when errors occur you do not receive them from STDOUT (which you are capturing). Try:

CopyBufferedReader input = new BufferedReader(new InputStreamReader(
               pr.getErrorStream()));
Answer from hkd93 on Stack Overflow
🌐
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)
I tried to modify your first example to run telnet, but nothing happened. Mir. ... You can invoke command line program(s) by saying: Runtime rt = Runtime.getRuntime(); String[] cmd = new String[2]; cmd[0] = "cmd /c mkdir " + destDir; rt.exec(cmd[0]); Hope this helps.
Discussions

linux - How to tell Java run this Runtime.getRuntime().exec, without waiting what ever command it has to run, simply run it in backend? - Stack Overflow
So any call to exec() should not block unless you used waitFor() on the returned process of the Runtime . Here is a small example(Exception handling omitted): CopyProcess p=Runtime.getRuntime().exec("cmd.exe /c ping 127.0.0.1 -n 10"); System.out.println("Here 1");//this will execute immediately ... More on stackoverflow.com
🌐 stackoverflow.com
How to use Runtime.getRuntime().exec() or ProcessBuilder or anyother way to execute a complex/hybrid unix/linux command in java - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Now available on Stack Overflow for Teams! AI features where you work: search, IDE, and chat More on stackoverflow.com
🌐 stackoverflow.com
September 11, 2018
java - Runtime exec on linux - Stack Overflow
For example: gnome-terminal -e "some command" runs some command in a new console, closing the console when the command exits. gnome-terminal -e "bash -c \"some command" ; sleep 10\" runs some command in a new console, waiting for 10 seconds before closing. Other console / terminal emulators will probably do this differently ... The final step is to use Runtime.exec... More on stackoverflow.com
🌐 stackoverflow.com
Java Runtime.getRuntime().exec() with Linux not working - Stack Overflow
So, I've been developing an application in Java, for Windows, Linux and Mac. It uses commandline applications to compress/decompress some data, and as I try to make it work with wine, I cant seem t... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/javahelp › problem with runtime.exec() method and using multiple commands in linux
r/javahelp on Reddit: Problem with Runtime.exec() method and using multiple commands in Linux
September 16, 2019 -

I am new to both Java and Linux, I was trying to use some Runtime.exec() commands that would allow my program to execute commands in Linux such as cd /mnt/ and ls --group-directories-first to list files and directories contained in /mnt/ but I think I am making a problem with the execution.

I tried my code to only include the ls --group-directories-first and it worked like a charm, only problem was, it only listed subdirectories and files in the projects folder. I wanted to make my program go to /mnt/ first so I made my command line to a command array by using exec(String[] cmdarray) format as p = Runtime.getRuntime().exec(new String[]{"cd /mnt/","ls --group-directories-first"}); and when I ran it on linux, it just got executed without any error but also without any feedback/printed lines.

Here is my code:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class linCom {
    public static void main(String args[]) {
        String s;
        Process p;

        try {
            p = Runtime.getRuntime().exec("ls --group-directories-first");
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}


    }
}

This worked and printed out:

line: DummyFolder1

line: linCom.class

line: linCom.java

exit: 0

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class linCom {
    public static void main(String args[]) {
        String s;
        Process p;

        try {
            p = Runtime.getRuntime().exec(new String[]{"cd /mnt/","ls --group-directories-first"});
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}


    }
}

This just got executed with no errors but also no prints on the screen.

I expected my program to just go to the /mnt/ directory and print out subdirectories and files on there, but it just got executed with no errors and no printed lines.

I have looked at other entries but could not find any answer to my problem.

🌐
Cmsimike
cmsimike.com › blog › 2010 › 11 › 15 › linux-runtime.getruntime.exec...-and-quotes
Linux, Runtime.getRuntime().exec(...) and quotes // Mike Megally
November 15, 2010 - Unfortunately I don’t know why, but in Linux (at least Ubuntu), the quotes are taken as part of the name. Take this example: Process p = Runtime.getRuntime().exec("\"ls\""); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); System.out.println(br.readLine());
🌐
Stack Overflow
stackoverflow.com › questions › 52268703 › how-to-use-runtime-getruntime-exec-or-processbuilder-or-anyother-way-to-exec
How to use Runtime.getRuntime().exec() or ProcessBuilder or anyother way to execute a complex/hybrid unix/linux command in java - Stack Overflow
September 11, 2018 - String myCommand = "for i in `cat ./files/logs1.txt | grep -o '[[:digit:]]*' | cut -c 1-3 | sort| uniq -c | sort -nr | sed 1d | head -n 10 | awk '{print $2}' `; do grep ^$i ./files/logs1.txt > $i.txt; done"; Process p = r.exec(new String[] { "bash", "-c", myCommand }); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); ... Your example code seems to work, when all needed stuff is added around it.
🌐
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 - For testing, we’ll use this Java example: import java.io.*; public class Exec { public static void main(String[] args) throws IOException { Process p = Runtime.getRuntime().exec(args[0]); byte[] b = new byte[1]; while (p.getErrorStream().read(b) > 0) System.out.write(b); while (p.getInputStream().read(b) > 0) System.out.write(b); } } 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: $ java Exec 'command arg1 arg2 ...'
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - String[] cmd2 = {"ls", "-l", "/path/to/directory"}; Process process2 = Runtime.getRuntime().exec(cmd2); int exitCode2 = process2.waitFor(); System.out.println("Variant 2 - Exit Code: " + exitCode2); // Variant 3: exec(String[] cmdarray, String[] ...
🌐
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 - So, we can create the whole command where we want to use pipe and pass it to .exec(): if (IS_WINDOWS) { process = Runtime.getRuntime() .exec(String.format("cmd.exe /c dir %s | findstr \"Desktop\"", homeDirectory)); } else { process = ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Runtime.html
Runtime (Java Platform SE 7 )
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
🌐
Stack Overflow
stackoverflow.com › questions › 26964746 › java-runtime-getruntime-exec-with-linux-not-working
Java Runtime.getRuntime().exec() with Linux not working - Stack Overflow
wine "/path/to/executable" "/path/to/argument" /bin/bash -c wine "/path/to/executable" "/path/to/argument" /bin/bash -c "wine "/path/to/executable" "/path/to/argument"" startx wine "/path/to/executable" "/path/to/argument" startx /bin/bash -c wine "/path/to/executable" "/path/to/argument" xterm -e wine "/path/to/executable" "/path/to/argument" xterm -e /bin/bash -c wine "/path/to/executable" "/path/to/argument" All of the above (aside from startx) do work on the Terminal of Linux, and none do with Java. At this point, I am pretty clueless as to what to do. I cant figure this out at all, and am just confused. I am not very familiar with Linux either, so it just adds more confusion. Just for reference, here is example of what I'd use to try to run first example command: Runtime.getRuntime().exec("wine \"/path/to/executable\" \"/path/to/argument\"").waitFor();
🌐
Coderanch
coderanch.com › t › 564537 › java › Runtime-getRuntime-exec-cmd-work
Runtime getRuntime() exec(cmd[]) - How does this work? (Java in General forum at Coderanch)
January 15, 2012 - If your process's stderr or stdout streams fill up with content, they will lock up your process; this causes problems for a LOT of people when they execute native code through Java. In short, you need to create threads that will read the content from the stdout and stderr streams after you execute the command (rt.exec() line). Read this article and see page 4 for a good example about it (it's the StreamGobbler class).
🌐
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); } } Sign up for free to join this conversation on GitHub.
🌐
OpenJDK
openjdk.org › jeps › 8263697
JEP draft: Safer Process Launch by ProcessBuilder and Runtime.exec
String[] args = {"java", "Hello", "Now is the time."}; Process p = Runtime.getRuntime().exec(args); -or- Process p = new ProcessBuilder(args).start(); To run a command dir and use a shell pipe to display the contents. When invoking a normal executable, such as dir the characters are not quoted ...
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;
}
🌐
Oracle Communities
community.oracle.com › thread › 1824473
Runtime.exec() on linux | Oracle Community
Using Runtime.exec, Runtime rt = Runtime.getRuntime(); rt.exec(". ./.bash_profile"); //fails,like "ls" fails and "mkdir' works rt.exec("export WOW_ROOT=/usr/bin"); //also fails rt.exec("declare WOW_ROOT=/usr/bin");//fails, can u tell i was gettin desperate by now? rt.exec("source ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-runtime-class-in-java
Java.lang.Runtime class in Java - GeeksforGeeks
May 6, 2022 - // Java Program to Illustrate Runtime ... Process process = Runtime.getRuntime().exec( "google-chrome"); System.out.println( "Google Chrome successfully started"); } // Catch block to handle the exceptions catch (Exception e) { ...
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - Example 26-2. ExecAndPrint.java (partial listing) /** Need a Runtime object for any of these methods */ protected static Runtime r = Runtime.getRuntime( ); /** Run the command given as a String, printing its output to System.out */ public static ... Read now · Unlock full access ·
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
Kevin Boone
kevinboone.me › exec.html
How to run a shell script from a Java application - Kevin Boone
On Linux the shell won't necessarily look in the current directory, although it might look in the directories specified in $PATH. If the script is in the working directory of the Java application, you probably need to do this: Process p · = Runtime · . getRuntime · ().exec ·