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.

Answer from Senthil 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 - Collect Linux command output - Stack Overflow
I follow the List4.7 and gave a command line "top -n 1", it prints out ERROR> top: failed tty get ERROR> ExitValue: 1 2011-06-24T11:51:43.783Z+00:00 ... @user: in that case, you're probably running into a limitation of top: It wants a real terminal to be its output and not just a stream. More on stackoverflow.com
🌐 stackoverflow.com
linux - Getting output from executing a terminal command in a java code running inside Cubieboard Platform - Stack Overflow
The code that I am using for running a terminal command in Linux Debian and getting the output inside a java program is this: public static String execute(String command) { StringBuilder sb = ... More on stackoverflow.com
🌐 stackoverflow.com
March 10, 2014
How to make the output of a Java program run on command line?
ImageMagick is an executable. A simple Google search leads here: https://stackoverflow.com/questions/13991007/execute-external-program-in-java More on reddit.com
🌐 r/learnprogramming
4
1
August 30, 2019
Java run terminal command and send input - Stack Overflow
I have master password for terminal setup and I would like to create a Java program which adds a few extra features. To do this I need to send and receive input/output from the terminal. I tried what was suggested in Java Program that runs commands with Linux Terminal but didn't have any luck. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Coderanch
coderanch.com › t › 751548 › java › Execute-Linux-Command-Return-Output
Execute Linux Command and Return Output (Java in General forum at Coderanch)
May 9, 2022 - I am working on a project that has to execute commands on the Linux terminal and I would like Java to handle the logic but I am having a bit of difficulty. I found the code below online and modified it a little to meet my needs. When it executes, I receive no output. But when I run something like "ifconfig" or "echo HelloWorld", I get ...
🌐
CodeJava
codejava.net › java-se › file-io › execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - From the Process object we can get outputs from and send inputs to the command. The following code snippet explains the principle: String command = "command of the operating system"; Process process = Runtime.getRuntime().exec(command); // deal with OutputStream to send inputs process.getO...
🌐
Viralpatel
viralpatel.net › how-to-execute-command-prompt-command-view-output-java
How to execute a command prompt command & view output in Java
May 25, 2009 - Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("ping localhost"); Code language: Java (java)The command (I’ve used “ping localhost” ) can be anything that your command prompt recognizes. It will vary on UNIX and Windows environment. Now comes the bit where you would want to see the output of the execution.
🌐
Crunchify
crunchify.com › macos tutorials › how to run windows, linux, macos terminal commands in java and return complete result
How to Run Windows, Linux, macOS terminal commands in Java and return complete Result • Crunchify
February 26, 2019 - What you do with the output of the command executed is entirely up to you and the application you’re creating. The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.
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.
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it's in. By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute ...
🌐
YouTube
youtube.com › watch
java run terminal command and get output - YouTube
Get Free GPT4o from https://codegive.com running terminal commands from a java application can be accomplished using the `processbuilder` or `runtime` class...
Published   October 31, 2024
🌐
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 create a process builder for each isolated command and compose them into the pipeline: @Test public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { List<ProcessBuilder> builders = Arrays.asList( new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), new ProcessBuilder("wc", "-l")); List<Process> processes = ProcessBuilder.startPipeline(builders); Process last = processes.get(processes.size() - 1); List<String> output = readOutput(last.getInputStream()); assertThat("Results should not be empty", output, is(not(empty()))); }
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - The .sh only contains one line of shell script ( a simple ‘ pm enable {packagename} ‘ command ). Would it be easier to put the command somewhere, or use the ‘ test.sh ‘ var? The best option is to make a link from text in an existing app (decompiled and manipulated in .smali dorm, via ‘APKEditor)… This was posted on a couole of sites, without solution. Hope you can help; cheers! ... Hello, When i run java from terminal than my shell command executes.
🌐
Java2s
java2s.com › example › java › native-os › execute-shell-command-and-get-output.html
execute Shell Command And Get Output - Java Native OS
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Main{ public static void main(String[] argv) throws Exception{ String command = "java2s.com"; System.out.println(executeCommandAndGetOutput(command)); }//from www . j av a2s .c o m public static String executeCommandAndGetOutput(String command) throws Exception { Process proc = createAndExecuteProcess(command); logForProc(proc); return getOuputMessageOfCommand(proc.getInputStream()); } private static Process createAndExecuteProcess(String co
Top answer
1 of 2
2

the code is right, just in the second line, I changed

"/bin/sh" to "/bin/bash"

And everything works!

sh == bash?

For a long time, /bin/sh used to point to /bin/bash on most GNU/Linux systems. As a result, it had almost become safe to ignore the difference between the two. But that started to change recently.

Some popular examples of systems where /bin/sh does not point to /bin/bash (and on some of which /bin/bash may not even exist) are:

  1. Modern Debian and Ubuntu systems, which symlink sh to dash by default;

  2. Busybox, which is usually run during the Linux system boot time as part of initramfs. It uses the ash shell implementation.

  3. BSDs. OpenBSD uses pdksh, a descendant of the Korn shell. FreeBSD's sh is a descendant of the original UNIX Bourne shell.

For more information on this please refer to : Difference between sh and bash

2 of 2
2

There maybe the childProcess doesn't run to end

Please to try:

proc.waitFor()

and run read stdInput and stdError in other Thread before proc.waitFor().

Example:

public static String execute(String command) {
        String[] commands = new String[] { "/bin/sh", "-c", command };

        ExecutorService executor = Executors.newCachedThreadPool();
        try {
            ProcessBuilder builder = new ProcessBuilder(commands);

            /*-
            Process proc = builder.start();
            CollectOutput collectStdOut = new CollectOutput(
                    proc.getInputStream());
            executor.execute(collectStdOut);

            CollectOutput collectStdErr = new CollectOutput(
                    proc.getErrorStream());
            executor.execute(collectStdErr);
            // */

            // /*-
            // merges standard error and standard output
            builder.redirectErrorStream();
            Process proc = builder.start();
            CollectOutput out = new CollectOutput(proc.getInputStream());
            executor.execute(out);
            // */
            // child proc exit code
            int waitFor = proc.waitFor();

            return out.get();
        } catch (IOException e) {
            return e.getMessage();
        } catch (InterruptedException e) {
            // proc maybe interrupted
            e.printStackTrace();
        }
        return null;
    }

    public static class CollectOutput implements Runnable {
        private final StringBuffer buffer = new StringBuffer();
        private final InputStream inputStream;

        public CollectOutput(InputStream inputStream) {
            super();
            this.inputStream = inputStream;
        }

        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            BufferedReader reader = null;
            String line;
            try {
                reader = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append('\n');
                }
            } catch (Exception e) {
                System.err.println(e);
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }

        }

        public String get() {
            return buffer.toString();
        }
    }
🌐
Medium
beknazarsuranchiyev.medium.com › run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how to… | by Beknazar | Medium
April 24, 2022 - It’s quite helpful to know how to run the operating system processes via Java code. The ProcessBuilder class is used to build Process object. We specify the commands and other configurations in the ProcessBuilder. We work on actual execution with Process instance. For example to get the status code from the process, to get its id, to see the output, to wait, and to kill the process.
🌐
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - In this article, we will take a close look at the importance of shell command that minimizes the possibility of an error during your work and how to execute it within Java code. There are two possible ways: the first is the Runtime class and that’s the exec method, and the second is the ProcessBuilder instance.
🌐
Reddit
reddit.com › r/learnprogramming › how to make the output of a java program run on command line?
r/learnprogramming on Reddit: How to make the output of a Java program run on command line?
August 30, 2019 -

Hi everyone,

So i have a program that basically reads from a CSV and inputs the values into a Command Line command for image making using ImageMagick. My problem is, after i read from the file and iterate a system printline with all of my commands i want to use within command prompt, i dont know how to take those and then run them all in CMD.

Ex)

The CSV: 1234, 5678, 9012

The output: C:/users/Desktop/logo "imageMagick command here + 1234" C:/users/Desktop/logofolder/1234.png

The above is essentially the command i put together with all the values substituted where the numbers are in the line. I am doing a sample size of 50. So everything is outputted correctly, i just dont know how to "run" that output in (or send it to) the command line so that the console can do that task for me (The making of the images and placing them in the folder).

The output i make in Java can literally be copy and pasted into the command line for the output i desire, but i want to do this all in essentially 1 click instead of writing it all back to a csv and then copy/pasting it all into CMD.

Thank you all for any help you may be able to give me.

I'm sorry if this is really hard to understand, im still a beginner programmer and tried my best...