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;
}
🌐
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 - When working with Process, you must process the output. Otherwise you run the risk of deadlock. See When Runtime.exec() won't. That's an old article, but it's still relevant. In this case the solution is two-fold: redirect the error stream so there's only one stream to read from, and then read from that stream (or discard its contents). SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Boost this thread! ... DOS command in java program question..
🌐
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 - Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.Basically, to execute a system command, pass the command string to the exec() method of the Runtime class.
🌐
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 - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class RuntimeExec { public StreamWrapper getStreamWrapper(InputStream is, String type){ return new StreamWrapper(is, type); } private class StreamWrapper extends Thread { InputStream is = null; String type = null; String message = null; public String getMessage() { return message; } StreamWrapper(InputStream is, String type) { this.is = is; this.type = type; } public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer buf
🌐
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.
🌐
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 - @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()))); } In the above example, we’re searching for all the java files inside the src directory and piping the results into another process to count them. To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements. As we’ve seen in this quick tutorial, we can execute a shell command in Java in two distinct ways.
Find elsewhere
🌐
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 - Invoking the exec method returns a Process object for managing the subprocess. Then you use the getInputStream() and getErrorStream() methods of the Process object to read the normal output of the command, and the error output of the command.
🌐
Blogger
coreygoldberg.blogspot.com › 2008 › 06 › java-run-system-command-and-return.html
Corey Goldberg: Java - Run a System Command and Return Output
Run a system command and return output: import java.io.*; public static String cmdExec(String cmdLine) { String line; String output = ""; try { Process p = Runtime.getRuntime().exec(cmdLine); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { output += (line + '\n'); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } return output; } Sample Usage: public static void main(String[] args) { CmdExec cmd = new CmdExec(); System.out.println(cmd.run("ls -a")); } Posted by ·
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - An example to execute a ping command and print out its output. ... import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ProcessBuilderExample1 { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); // Windows processBuilder.command("cmd.exe", "/c", "ping -n 3 google.com"); try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println("\nExited with error code : " + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
🌐
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
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - Taking a look at how the ProcessBuilder takes our input from the exec() method and runs the command, gives us a good idea of how to use it as well. It accepts a String[] cmdarray, and that's enough to get it running.
🌐
Alvin Alexander
alvinalexander.com › java › edu › pj › pj010016
Running system commands in Java applications | alvinalexander.com
June 4, 2016 - Because you can't create your own instance of the Runtime class, you first use the getRuntime method to access the current runtime environment and then invoke the Runtime exec method. This returns a Process object. Everything else you do involves methods of the Process object. In this case, because we're running the "ps -ef" command on a Unix system, we just need to read the output of the command.
🌐
GitHub
gist.github.com › gersp › 1885878
Execute system command from java and grab result into String · GitHub
Execute system command from java and grab result into String - ExecUtils.java