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;
}
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
This example will capture the output (from stdio) of an external program. 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.
Discussions

runtime - read the output from java exec - Stack Overflow
public static void main(String[] ... pr = Runtime.getRuntime().exec("java -version"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } pr.waitFor(); System.out.println("ok!"); in.close(); System.exit(0); } in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return ... More on stackoverflow.com
🌐 stackoverflow.com
java - display the output-stream of a Process returned by Runtime.exec() - Stack Overflow
I believe you are trying to get the output from process, and for that you should get the InputStream. InputStream is = Runtime.getRuntime().exec("ls").getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader buff = new BufferedReader (isr); String line; while((line ... More on stackoverflow.com
🌐 stackoverflow.com
java - Printing Runtime exec() OutputStream to console - Stack Overflow
I am trying to get the OutputStream of the Process initiated by exec() to the console. How can this be done? ... import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; public class RuntimeTests ... More on stackoverflow.com
🌐 stackoverflow.com
Java Runtime Exec not outputting what I expect
How do I get it to output the same as typing in "javac -help"? ... Archived post. New comments cannot be posted and votes cannot be cast. Share ... Also, java actually has a compiler API and it might make sense to use that rather than to fiddle with calling javac from within your program. ... You might have to do "cmd javac" Look at how to do Java exec for "cd" where they explain why it won't work ... I'm on a Linux computer. Runtime... More on reddit.com
🌐 r/javahelp
8
1
June 3, 2016
🌐
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.
🌐
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.
🌐
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 - Knute Snortum wrote:. . . Good point. I think it is more complicated; you have to get a return value from waitFor(). But it is all described really clearly by Daconta. ... Boost this thread! ... DOS command in java program question..
🌐
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
🌐
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 - String command = "command of the operating system"; Process process = Runtime.getRuntime().exec(command); // deal with OutputStream to send inputs process.getOutputStream(); // deal with InputStream to get ordinary outputs process.getInputStream(); // deal with ErrorStream to get error outputs process.getErrorStream();Now, let’s walk through some real code examples.The following code snippet runs the ping command on Windows and captures its output:
Find elsewhere
🌐
javathinking
javathinking.com › blog › java-runtime-getruntime-getting-output-from-executing-a-command-line-program
Java Runtime.getRuntime(): How to Capture Output from Executed Command Line Programs — javathinking.com
Example 2: Naive (Blocking) Output Capture · import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class NaiveOutputCapture { public static void main(String[] args) { try { // Command that writes to both stdout and stderr (Unix example) Process process = Runtime.getRuntime().exec("ls -l non_existent_file"); // Read stdout (naive: only read stdout, ignore stderr) InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); String line; System.out.println("Stand
🌐
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(); } } }
🌐
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 - Next, we’ll spawn a new process using the .exec() method and use the StreamGobler created previously. 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 { process = Runtime.getRuntime() .exec(String.format("/bin/sh -c ls %s", homeDirectory)); } StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), System.out::println); Future<?> future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); assertEquals(0, exitCode);
🌐
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 5
70

Use getErrorStream().

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

EDIT:

You can use ProcessBuilder (and also read the documentation)

ProcessBuilder   ps=new ProcessBuilder("java.exe","-version");

//From the DOC:  Initially, this property is false, meaning that the 
//standard output and error output of a subprocess are sent to two 
//separate streams
ps.redirectErrorStream(true);

Process pr = ps.start();  

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
pr.waitFor();
System.out.println("ok!");

in.close();
System.exit(0);
2 of 5
11

Note that we're reading the process output line by line into our StringBuilder. Due to the try-with-resources statement we don't need to close the stream manually. The ProcessBuilder class let's us submit the program name and the number of arguments to its constructor.

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

public class ProcessOutputExample
{
    public static void main(String[] arguments) throws IOException,
            InterruptedException
    {
        System.out.println(getProcessOutput());
    }

    public static String getProcessOutput() throws IOException, InterruptedException
    {
        ProcessBuilder processBuilder = new ProcessBuilder("java",
                "-version");

        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        StringBuilder processOutput = new StringBuilder();

        try (BufferedReader processOutputReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));)
        {
            String readLine;

            while ((readLine = processOutputReader.readLine()) != null)
            {
                processOutput.append(readLine + System.lineSeparator());
            }

            process.waitFor();
        }

        return processOutput.toString().trim();
    }
}

Prints:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
🌐
Tabnine
tabnine.com › home › code library
https://www.tabnine.com/code/java/methods/java.lan...
July 25, 2024 - The Tabnine Code Library is no longer available — but you can still get the answers and suggestions you need from our AI code assistant.
🌐
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(); } } }
🌐
Delft Stack
delftstack.com › home › howto › java › java runtime exec
Java Lang Runtime exec() Method in Java | Delft Stack
October 12, 2023 - package delftstack; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; // Main class public class Example { // Main driver method public static void main(String[] args) throws InterruptedException { try { // Use Runtime.getRuntime.exec on a separate process Process Demo_Process = Runtime.getRuntime().exec("java -version"); // Get the output in the console String Output_Line; InputStreamReader Input_Stream_Reader = new InputStreamReader(Demo_Process.getInputStream()); BufferedReader Buffered_Reader = new BufferedReader(Input_Stream_R
🌐
Coderanch
coderanch.com › t › 425969 › java › output-Runtime-getRuntime-exec
Help for getting output of Runtime.getRuntime().exec() (Java in General forum at Coderanch)
Runtime.getRuntime().exec("cmd/c start C:/jdk1.4/BIN/javac filename.java"); . My code is like this Anyone can help me please.
🌐
GitHub
gist.github.com › 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); } } Sign up for free to join this conversation on GitHub.